SQL and Java. Database Systems Lecture 19 Natasha Alechina

Similar documents
Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

How To Use The Database In Jdbc.Com On A Microsoft Gdbdns.Com (Amd64) On A Pcode (Amd32) On An Ubuntu (Amd66) On Microsoft

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Self-test Database application programming with JDBC

The JAVA Way: JDBC and SQLJ

JDBC (Java / SQL Programming) CS 377: Database Systems

LSINF1124 Projet de programmation

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

CS/CE 2336 Computer Science II

DEVELOPING MULTITHREADED DATABASE APPLICATION USING JAVA TOOLS AND ORACLE DATABASE MANAGEMENT SYSTEM IN INTRANET ENVIRONMENT

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

SQL and programming languages

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

CS346: Database Programming.

1 SQL Data Types and Schemas

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

Database Access Through Java Technologies

Java DataBase Connectivity (JDBC)

Making Oracle and JDBC Work For You

ASP.NET Programming with C# and SQL Server

Using Netbeans and the Derby Database for Projects Contents

Abstract. Introduction. Web Technology and Thin Clients. What s New in Java Version 1.1

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Database Application Development. Overview. SQL in Application Code. Chapter 6

Statement Level Interface. Call Level Interface. Static SQL. Status. Connections. Transactions. To connect to an SQL database, use a connect statement

Java Server Pages and Java Beans

To create a universal SQL client for accessing local or remote database ( 35.2). To execute SQL statements in a batch mode ( 35.3).

Package sjdbc. R topics documented: February 20, 2015

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

Part IV: Java Database Programming

How To Let A Lecturer Know If Someone Is At A Lecture Or If They Are At A Guesthouse

A Brief Introduction to MySQL

TECH TUTORIAL: EMBEDDING ANALYTICS INTO A DATABASE USING SOURCEPRO AND JMSL

Accesssing External Databases From ILE RPG (with help from Java)

A Generic Database Web Service

Java and RDBMS. Married with issues. Database constraints

Microsoft SQL Server Features that can be used with the IBM i

Prof. Edwar Saliba Júnior

An Eclipse Plug-In for Visualizing Java Code Dependencies on Relational Databases

Brazil + JDBC Juin 2001, douin@cnam.fr

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

public class ResultSetTable implements TabelModel { ResultSet result; ResultSetMetaData metadata; int num cols;

Week 5: Embedded SQL. Embedded SQL 4. Application Program. Interactive vs. Non-Interactive SQL. Update Statements

How To Use A Sas Server On A Java Computer Or A Java.Net Computer (Sas) On A Microsoft Microsoft Server (Sasa) On An Ipo (Sauge) Or A Microsas (Sask

Real SQL Programming. Embedded SQL Call-Level Interface Java Database Connectivity

Security Module: SQL Injection

Performance Tuning for the JDBC TM API

Working With Derby. Version 10.2 Derby Document build: December 11, 2006, 7:06:09 AM (PST)

Programming Database lectures for mathema

Implementing the Shop with EJB

Using Temporary Tables to Improve Performance for SQL Data Services

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

Oracle 10g PL/SQL Training

Achieving Database Interoperability Across Data Access APIs through SQL Up-leveling

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Spring Data JDBC Extensions Reference Documentation

Applets, RMI, JDBC Exam Review

More SQL: Assertions, Views, and Programming Techniques

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

FileMaker 13. ODBC and JDBC Guide

Introduction Web Portal Main Page Group Management Create group Modify Group Member List... 5

CSI 2132 Lab 8. Outline. Web Programming JSP 23/03/2012

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

Apéndice C: Código Fuente del Programa DBConnection.java

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Using the SQL TAS v4

FileMaker 11. ODBC and JDBC Guide

How I hacked PacketStorm ( )

Chapter 7 -- Adding Database Support

Building Web Applications, Servlets, JSP and JDBC

Database System Concepts

Java and Microsoft Access SQL Tutorial

2. Follow the installation directions and install the server on ccc

1 File Processing Systems

Assignment 3 Version 2.0 Reactive NoSQL Due April 13

SQL Data Definition. Database Systems Lecture 5 Natasha Alechina

ODBC Chapter,First Edition

Using JML to protect Java code against SQL injection. Johan Janssen June 26, 2007

Porting from Oracle to PostgreSQL

Oracle Fusion Middleware

Developing SQL and PL/SQL with JDeveloper

Database System Security. Paul J. Wagner UMSSIA 2008

Transcription:

Database Systems Lecture 19 Natasha Alechina

In this Lecture SQL in Java SQL from within other Languages SQL, Java, and JDBC For More Information Sun Java tutorial: http://java.sun.com/docs/books/tutorial/jdbc Connolly and Begg 29.7

SQL and Other Languages Combining SQL and another language Use SQL to run queries on the database Use another language (Java, C, etc) to do the rest of the work: e.g. user interface, or complicated processing Need an interface between the two ODBC (Open DB Connectivity) is a common standard Provides an API which is widely supported Allows you to pass queries to a database, and return the results to a program

JDBC JDBC is a Java API for database connectivity It is not the same as ODBC but implements a similar specification JDBC enables programmers to write java applications that Connect to a database Send queries and update statements to the database Retrieve and process the results received from the database in answer to the query

JDBC

JDBC JDBC consists of: The JDBC API proper: interfaces, classes and methods for executing SQL statements, retrieving results, and propagating changes back to the database JDBC Driver Manager: a class that defines objects which can connect Java applications to a JDBC driver. JDBC Test Suite JDBC-ODBC Bridge

Using JDBC Basic steps when using JDBC Register a database driver Open a connection Pass some queries to the database Process the results as needed Close the connection Deal with any errors Preamble: import java.sql.*;

Register a Driver We need to register an appropriate driver with the DriverManager There is a different driver for each DBMS We ll need to use the driver for Oracle: DriverManager.registerDriver( new oracle.jdbc.driver.oracledriver() );

Open a Connection Next we open a connection to the database from the DriverManager We give the address of the database, a username and a password Connection conn = DriverManager.getConnection ( "jdbc:oracle:thin:@oracle.cs.nott.ac.uk:1521:maindb", xxx06u", somepassword"); Your username Your sqlplus password

Passing Queries to the DB Now we can send queries to the DB We do this through a Statement object Each Statement can deal with one query at a time A single Connection can have several statements open at any time Statement objects Are created from a Connection The executeupdate() method runs a query that doesn t return any results (UPDATE, CREATE TABLE, etc) executequery() is used when a result is expected

Passing Queries to the DB Statement sttable = conn.createstatement(); sttable.executeupdate( "CREATE TABLE Fruit(Name VARCHAR(10),Amount INT) ); sttable.close(); Statement stinsert1 = conn.createstatement(); stinsert1.executeupdate( "INSERT INTO Fruit VALUES('Apple', 5) ); stinsert1.close();

Passing Queries to the DB Statement stinsert2 = conn.createstatement(); stinsert2.executeupdate( "INSERT INTO Fruit VALUES( Pumpkin', 1) ); stinsert2.close();

Processing Query Results When a query returns a result We use the Statement object s executequery method The results are put in a ResultSet object Each Statement can deal with a single ResultSet at any one time The ResultSet object Is essentially a table Has a cursor that points to the current row of data Initially the cursor is positioned before the first row The next() method moves to the next row, and returns false if there isn t one

Processing Query Results Statement stresult = conn.createstatement(); ResultSet fruit = stresult.executequery( "SELECT * FROM Fruit" ); while(fruit.next()) { System.out.println( fruit.getstring("name")+ ", " + fruit.getint("amount")); } fruit.close();

Working with ResultSets We get values from the ResultSet with getint() getstring() getdouble() etc. Each takes either The name of the column as a String, or The index of the column as an integer

Advanced ResultSets By default a ResultSet Allows you to go over the results once, from start to finish Allows you to read, but not change, the information in the result We can change this behaviour so that We can move forward and backwards We can update existing rows We can add rows This is decided when we create the Statement object from the Connection

Creating Statements Again conn.createstatement(<scroll>, <update>); <scroll> is one of ResultSet.TYPE_FORWARD_ONLY ResultSet.TYPE_SCROLL_SENSITIVE ResultSet.TYPE_SCROLL_INSENSITIVE <update> is one of ResultSet.CONCUR_READ_ONLY ResultSet.CONCUR_UPDATABLE

Scrollable ResultSets If we use the option TYPE_SCROLL_SENSITIVE or TYPE_SCROLL_INSENSITIVE We can move around the ResultSets made from that statement There are a lot of options available for this For a result set called rs rs.first(); rs.absolute(1) rs.absolute(2) rs.absolute(3) rs.relative(-2) rs.previous(); rs.relative(-1) Current row rs.next(); rs.relative(1) rs.relative(2) rs.absolute(-3) rs.absolute(-2) rs.last(); rs.absolute(-1)

Updating ResultSets If we use the option CONCUR_UPDATABLE We can update the values in the result set or add a new row In Oracle you can t have an updatable forward-only result set Also in Oracle you have to explicitly specify the columns in your SELECT statement if you want to update it (no SELECT * )

Updating a Row // Make an updatable Statement Statement result2 = conn.createstatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rset2 = result2.executequery( "SELECT Name, Amount FROM Fruit"); rset2.absolute(2);// set current row to second rset2.updateint("amount", 3); // rset2.updaterow(); // updates the second row

Inserting a Row // rset2 is set up as in the previous example // Get ready to insert a row rset2.movetoinsertrow(); // Put the values of the new row in each column rset2.updatestring( Name", Orange ); rset2.updateint( Amount", 7); // Add this row rset2.insertrow(); // Go back to the row we were at before inserting rset2.movetocurrentrow();

Dealing with Errors Things can go wrong with all of this Incorrect SQL statements DBMS might not be available DBMS might not support some features If something goes wrong then an SQLException occurs If an exception is thrown: We need to deal with it as best we can Make sure any database objects are closed If a connection is left open it can consume resources and might interfere with later use of the database

Exception Handling // Declaration of any database objects try { // Some database code } catch (Exception e) { // Error reporting etc. } finally { // Make sure all database objects are // closed and cleaned up }

Closing Objects To make sure the object is closed See if the object exists If it does, call its close method This might throw an exception itself, which needs to be caught At some stage we have to stop handling the exceptions Connection conn; try {... } finally { if (conn!= null) { try { conn.close(); } catch (...) { // what to do? } } }

That s it If you have revision questions, please contact me.