CS6320 - JDBC

30
CS6320 - JDBC CS6320 - JDBC

description

CS6320 - JDBC. Introducing JDBC. JDBC: is an API that provides “universal data access for the Java2 platform” Allows you to connect to a known data source using common OO semantics using Java Allows you to issue standard SQL commands on that data source - PowerPoint PPT Presentation

Transcript of CS6320 - JDBC

Page 1: CS6320 - JDBC

CS6320 - JDBCCS6320 - JDBC

Page 2: CS6320 - JDBC

Introducing JDBCIntroducing JDBC JDBC: is an API that provides JDBC: is an API that provides

“universal data access for the “universal data access for the Java2 platform”Java2 platform”Allows you to connect to a Allows you to connect to a known data source using known data source using common OO semantics using common OO semantics using JavaJava

Allows you to issue standard SQL Allows you to issue standard SQL commands on that data sourcecommands on that data source

Provides you with classes to Provides you with classes to facilitate access to and facilitate access to and manipulation of:manipulation of:• returned data and, returned data and, • generated exceptionsgenerated exceptions

Page 3: CS6320 - JDBC

JDBC Driver TypesJDBC Driver Types

Type 1 (JDBC-ODBC Bridge Type 1 (JDBC-ODBC Bridge Technology)Technology)

Type 2 (JNI drivers for native Type 2 (JNI drivers for native connection libraries)connection libraries)

Type 3 (Socket-level Middleware Type 3 (Socket-level Middleware Translator)Translator)

Type 4 (Pure Java-DBMS driver)Type 4 (Pure Java-DBMS driver)

Page 4: CS6320 - JDBC

Driver TypesDriver Types

Type 1 Type 2 Type 3 Type 4

Page 5: CS6320 - JDBC

Type 1 Drivers: Type 1 Drivers: JDBC-ODBC BridgesJDBC-ODBC Bridges

JDBC driver translates call into JDBC driver translates call into ODBC and redirects ODBC call to ODBC and redirects ODBC call to an ODBC driver on the DBMSan ODBC driver on the DBMS

ODBC binary code must exist on ODBC binary code must exist on every clientevery client

Translation layer compromises Translation layer compromises execution speed to small degreeexecution speed to small degree

Page 6: CS6320 - JDBC

Type 2 Drivers: Type 2 Drivers: Native-API + Java DriverNative-API + Java Driver

Java driver makes JNI calls on the client Java driver makes JNI calls on the client API (usually written in C or C++)API (usually written in C or C++)• eg: Sybase dblib or ctlibeg: Sybase dblib or ctlib• eg: Oracle Call Interface libs (OCI)eg: Oracle Call Interface libs (OCI)

Requires client-side code to be Requires client-side code to be installedinstalled

Often the fastest solution availableOften the fastest solution available Native drivers are usually delivered by Native drivers are usually delivered by

DBMS vendorDBMS vendor Bug in driver can crash JVMsBug in driver can crash JVMs

Page 7: CS6320 - JDBC

Type 3 Drivers:Type 3 Drivers:JDBC-Middleware Pure Java DriverJDBC-Middleware Pure Java Driver

JDBC driver translates JDBC calls into a DBMS-JDBC driver translates JDBC calls into a DBMS-independent protocolindependent protocol

Then, communicates over a socket with a Then, communicates over a socket with a middleware server that translates Java code middleware server that translates Java code into native API DBMS callsinto native API DBMS calls

No client code need be installedNo client code need be installed Single driver provides access to multiple Single driver provides access to multiple

DBMSs, eg. WebLogic, Tengah driversDBMSs, eg. WebLogic, Tengah drivers Type 3 drivers auto-download for applets.Type 3 drivers auto-download for applets. Communication is indirect via a middleware Communication is indirect via a middleware

serverserver

Page 8: CS6320 - JDBC

Type 4 Drivers:Type 4 Drivers:Pure Java DriversPure Java Drivers

Java drivers talk directly to the DBMS Java drivers talk directly to the DBMS using Java socketsusing Java sockets

No Middleware layer needed, access is No Middleware layer needed, access is direct.direct.

Simplest solution available.Simplest solution available. No client code need be installed.No client code need be installed. Type 4 drivers auto-download for appletsType 4 drivers auto-download for applets

Page 9: CS6320 - JDBC

JDBC DriversJDBC Drivers

JDBC drivers exist for every major JDBC drivers exist for every major database including: Oracle, SQL database including: Oracle, SQL Server, Sybase, and MySQL.Server, Sybase, and MySQL.

Page 10: CS6320 - JDBC

Six Steps to Using JDBC (simple Six Steps to Using JDBC (simple program…no connection program…no connection

pooling/middleware)pooling/middleware)1.1. Load the JDBC DriverLoad the JDBC Driver

2.2. Establish the Database ConnectionEstablish the Database Connection

3.3. Create a Statement ObjectCreate a Statement Object

4.4. Execute a QueryExecute a Query

5.5. Process the ResultsProcess the Results

6.6. Close the ConnectionClose the Connection

Page 11: CS6320 - JDBC

A standard simple JDBC applicationA standard simple JDBC application// // Load the JDBC driverLoad the JDBC driverClass.forName("oracle.jdbc.OracleDriver").newInstance();Class.forName("oracle.jdbc.OracleDriver").newInstance();// // Connect to the databaseConnect to the databaseConnection conn = DriverManager.getConnection Connection conn = DriverManager.getConnection

((connect-stringconnect-string,,useruser, , passpass););// // Create a statementCreate a statement Statement stmt = conn.createStatement ();Statement stmt = conn.createStatement ();// // Execute the statement: select data from the emp tableExecute the statement: select data from the emp table boolean results = stmt.execute("select * from emp");boolean results = stmt.execute("select * from emp"); ResultSet rset = null;ResultSet rset = null; if (results) rset = stmt.getResultSet();if (results) rset = stmt.getResultSet();

// // Process results: walk through the result set Process results: walk through the result set while (rset.next ()) {while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2));System.out.println (rset.getString (1) + rset.getString(2));

… …..}}

Page 12: CS6320 - JDBC

Overview: Connecting to a Overview: Connecting to a DatabaseDatabase

// Load the Oracle JDBC driver// Load the Oracle JDBC driverClass.forName("oracle.jdbc.OracleDriver").newInstance();Class.forName("oracle.jdbc.OracleDriver").newInstance();// Connect to the database// Connect to the databaseConnection conn = DriverManager.getConnection Connection conn = DriverManager.getConnection

((connect-stringconnect-string,,useruser, , passpass););// Create a statement// Create a statement Statement stmt = conn.createStatement ();Statement stmt = conn.createStatement ();// Select data from the emp table// Select data from the emp table boolean results = stmt.execute("select * from emp");boolean results = stmt.execute("select * from emp"); ResultSet rset = null;ResultSet rset = null; if (results) rset = stmt.getResultSet();if (results) rset = stmt.getResultSet();

// Walk through the result set // Walk through the result set while (rset.next ()) {while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2));System.out.println (rset.getString (1) + rset.getString(2));

… …..}}

Page 13: CS6320 - JDBC

The JDBC Driver ManagerThe JDBC Driver Manager

Management layer of JDBC, interfaces Management layer of JDBC, interfaces between the client and the driver.between the client and the driver.• Keeps a list of available driversKeeps a list of available drivers• Manages driver login time limits and Manages driver login time limits and

printing of log and tracing messagesprinting of log and tracing messages Secure because manager will only allow Secure because manager will only allow

drivers that come from local file system drivers that come from local file system or the same initial class loader or the same initial class loader requesting a connectionrequesting a connection

Most popular use: Most popular use: • Connection getConnection(url, id, passwd);Connection getConnection(url, id, passwd);

Page 14: CS6320 - JDBC

Create a Connection to the Create a Connection to the databasedatabase

Call the getConnection method on the Call the getConnection method on the DriverManager.DriverManager.

Connection conn = Connection conn = DriverManager.getConnection(url, login, DriverManager.getConnection(url, login,

password)password)

URLs:URLs:• ““jdbc:sybase:Tds:skunk:4100/myDB”jdbc:sybase:Tds:skunk:4100/myDB”• "jdbc:oracle:thin:@limani.cs.uchicago.edu"jdbc:oracle:thin:@limani.cs.uchicago.edu

:1521:cs51024";:1521:cs51024"; Only one requirement: the relevant Only one requirement: the relevant

Drivers must be able to recognize Drivers must be able to recognize their own URLtheir own URL

Page 15: CS6320 - JDBC

Overview: StatementsOverview: Statements// Load the Oracle JDBC driver// Load the Oracle JDBC driverClass.forName("oracle.jdbc.OracleDriver").newInstance();Class.forName("oracle.jdbc.OracleDriver").newInstance();// Connect to the database// Connect to the databaseConnection conn = DriverManager.getConnection Connection conn = DriverManager.getConnection

((connect-stringconnect-string,,useruser, , passpass););// Create a statement// Create a statement Statement stmt = conn.createStatement ();Statement stmt = conn.createStatement ();// Select data from the emp table// Select data from the emp table boolean results = stmt.execute("select * from emp");boolean results = stmt.execute("select * from emp"); ResultSet rset = null;ResultSet rset = null; if (results) rset = stmt.getResultSet();if (results) rset = stmt.getResultSet();

// Walk through the result set // Walk through the result set while (rset.next ()) {while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2));System.out.println (rset.getString (1) + rset.getString(2));

… …..}}

Page 16: CS6320 - JDBC

SQL StatementsSQL Statements

Types of statements:Types of statements: Class Class StatementStatement

• Represents a basic SQL statementRepresents a basic SQL statement• Statement stmt = conn.createStatement();Statement stmt = conn.createStatement();

Class Class PreparedStatementPreparedStatement• A A precompiledprecompiled SQL statement, which can offer SQL statement, which can offer

improved performance, especially for improved performance, especially for large/complex SQL statementslarge/complex SQL statements

Class Class CallableStatementCallableStatement • Allows JDBC programs access to stored Allows JDBC programs access to stored

proceduresprocedures

Can be used for both DDL and DML commandsCan be used for both DDL and DML commands

Page 17: CS6320 - JDBC

Execute an SQL StatementExecute an SQL Statement executeQueryexecuteQuery(): execute a query and get a ResultSet back(): execute a query and get a ResultSet back executeUpdateexecuteUpdate(): execute an update and get back an int (): execute an update and get back an int

specifying number of rows acted onspecifying number of rows acted on• UPDATE [table] set [column_name] = value where […]UPDATE [table] set [column_name] = value where […]• DELETE from [table] where [column_name] = 5DELETE from [table] where [column_name] = 5

executeexecute(): exec. unknown SQL, returns true if a resultSet is (): exec. unknown SQL, returns true if a resultSet is available:available:

Statement genericStmt = conn.createStatement();Statement genericStmt = conn.createStatement();if( genericStmt.execute(SQLString)) {if( genericStmt.execute(SQLString)) {

ResultSet rs = genericStmt.getResultSet(); ResultSet rs = genericStmt.getResultSet(); process(); }process(); }

else {else {int updated = genericStmt.getUpdateCount(); int updated = genericStmt.getUpdateCount(); processCount(); processCount();

}}……

Page 18: CS6320 - JDBC

Prepared StatementsPrepared Statements

Use for complex queries or repeated queriesUse for complex queries or repeated queries Features:Features:

• precompiled at database (statement usually sent to precompiled at database (statement usually sent to database immediately on creation for compilation)database immediately on creation for compilation)

• supply with new variables each time you call itsupply with new variables each time you call it Example:Example:

• PreparedStatement ps = PreparedStatement ps = conn.prepareStatement(“update table set sales = ? conn.prepareStatement(“update table set sales = ? Where custName = ?”);Where custName = ?”);

Set with values (use setXXX() methods on Set with values (use setXXX() methods on PreparedStatement:PreparedStatement:• ps.setInt(1, 400000);ps.setInt(1, 400000);• ps.setString(2, “United Airlines”);ps.setString(2, “United Airlines”);

Then execute:Then execute:• int count = ps.executeUpdate();int count = ps.executeUpdate();

Page 19: CS6320 - JDBC

Overview: ResultSets and Overview: ResultSets and CursorsCursors

// Load the Oracle JDBC driver// Load the Oracle JDBC driverClass.forName("oracle.jdbc.OracleDriver").newInstance();Class.forName("oracle.jdbc.OracleDriver").newInstance();// Connect to the database// Connect to the databaseConnection conn = DriverManager.getConnection Connection conn = DriverManager.getConnection

((connect-stringconnect-string,,useruser, , passpass););// Create a statement// Create a statement Statement stmt = conn.createStatement ();Statement stmt = conn.createStatement ();// Select data from the emp table// Select data from the emp table boolean results = stmt.execute("select * from emp");boolean results = stmt.execute("select * from emp"); ResultSet rset = null;ResultSet rset = null; if (results) rset = stmt.getResultSet();if (results) rset = stmt.getResultSet();

// Walk through the result set // Walk through the result set while (rset.next ()) {while (rset.next ()) { System.out.println (rset.getString (1) + rset.getString(2));System.out.println (rset.getString (1) + rset.getString(2));

… …..}}

Page 20: CS6320 - JDBC

Result Sets and CursorsResult Sets and Cursors

Result Sets are returned from queries. Result Sets are returned from queries. Possible number of rows: zero, one, or Possible number of rows: zero, one, or

moremore Cursors are ‘Cursors are ‘iterators’iterators’ that can be user that can be user

to ‘walk’ through a result setto ‘walk’ through a result set JDBC 2.0 allows for backward as well JDBC 2.0 allows for backward as well

as forward cursors, including the as forward cursors, including the ability to go to a specific row or a ability to go to a specific row or a relative rowrelative row

Page 21: CS6320 - JDBC

Result SetsResult Sets Iterate over all rows:Iterate over all rows:

• ResultSet rs = stmt.executeQuery(“select id, price from ResultSet rs = stmt.executeQuery(“select id, price from inventory”);inventory”);

• rs.next(), rs.previous(), rs.first(), …rs.next(), rs.previous(), rs.first(), … call once to access first row: while(rs.next()) {}call once to access first row: while(rs.next()) {}

Extract data from the ResultSetExtract data from the ResultSet• getXXX(getXXX(columnNamecolumnName//indexValindexVal))

getInt()getInt() getDouble()getDouble() getString() (highly versatile, inclusive of others; getString() (highly versatile, inclusive of others;

automatic conversion to String for most types)automatic conversion to String for most types) getObject() (returns a generic Java Object)getObject() (returns a generic Java Object)

• rs.wasNull() - returns true if last get was Nullrs.wasNull() - returns true if last get was Null

Page 22: CS6320 - JDBC

Example :Example :Inserting Data via JDBCInserting Data via JDBC

Page 23: CS6320 - JDBC

import java.sql.*;

public class InsertCoffees {

public static void main(String args[]) throws SQLException { System.out.println ("Adding Coffee Data"); ResultSet rs = null; PreparedStatement ps = null; String url = "jdbc:mysql://localhost/cerami"; Connection con; Statement stmt; try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); }

1

Page 24: CS6320 - JDBC

try { con = DriverManager.getConnection(url); stmt = con.createStatement(); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); stmt.close(); con.close(); System.out.println ("Done"); } catch(SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }}

23

4

6

Page 25: CS6320 - JDBC

Example :Example :Querying Data via JDBCQuerying Data via JDBC

Page 26: CS6320 - JDBC

import java.sql.*;

public class SelectCoffees {

public static void main(String args[]) throws SQLException { ResultSet rs = null; PreparedStatement ps = null; String url = "jdbc:mysql://localhost/cerami"; Connection con; Statement stmt; try {

Class.forName("org.gjt.mm.mysql.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); }

try { con = DriverManager.getConnection(url);

stmt = con.createStatement();

1

23

Page 27: CS6320 - JDBC

ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close();

} catch(SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }}

4

5

6

Page 28: CS6320 - JDBC

Exception HandlingException Handling

SQL ExceptionsSQL Exceptions• Nearly every JDBC method can throw a Nearly every JDBC method can throw a SQLExceptionSQLException in response to a data access in response to a data access error error

• If more than one error occurs, they are If more than one error occurs, they are chained chained togethertogether

• SQL exceptions contain:SQL exceptions contain: Description of the error, Description of the error, getMessagegetMessage The SQLState (Open Group SQL specification) The SQLState (Open Group SQL specification)

identifying the exception, identifying the exception, getSQLStategetSQLState A vendor-specific integer, error code, A vendor-specific integer, error code, getErrorCodegetErrorCode A chain to the next A chain to the next SQLExceptionSQLException, , getNextExceptiongetNextException

Page 29: CS6320 - JDBC

SQL Exception ExampleSQL Exception Exampletry {try {

... // JDBC statement.... // JDBC statement.

} catch (} catch (SQLException sqleSQLException sqle) {) { while (sqle != null) {while (sqle != null) { System.out.println("Message: " + System.out.println("Message: " +

sqle.getMessage());sqle.getMessage()); System.out.println("SQLState: " + System.out.println("SQLState: " +

sqle.getSQLState());sqle.getSQLState()); System.out.println("Vendor Error: " +System.out.println("Vendor Error: " + sqle.getErrorCode());sqle.getErrorCode()); sqle.printStrackTrace(System.out);sqle.printStrackTrace(System.out); sqle = sqle = sqle.getNextException()sqle.getNextException();; }}}}

Page 30: CS6320 - JDBC

Using the JDBC MetaData Using the JDBC MetaData InterfaceInterface

ResultSet: ResultSet: ResultSetMetaData m = rs.getMetaData()ResultSetMetaData m = rs.getMetaData() ResultSetMetaData provides information about the types and ResultSetMetaData provides information about the types and

properties of the DDL properties of a ResultSet objectproperties of the DDL properties of a ResultSet object ResultSetMetaData provides various methods for finding out ResultSetMetaData provides various methods for finding out

information about the structure of a ResultSet:information about the structure of a ResultSet:• getColumnClassNamegetColumnClassName(int col): gets fully-qualified Java class (int col): gets fully-qualified Java class

name to which a column value will be mapped; eg. name to which a column value will be mapped; eg. Java.lang.Integer, etc.Java.lang.Integer, etc.

• getColumnCountgetColumnCount(): gets the number of columns in the (): gets the number of columns in the ResultSetResultSet

• getColumnNamegetColumnName(int col): gets the name of column(int col): gets the name of column• int int getColumnTypegetColumnType(int col): gets the JDBC type (java.sql.Types) (int col): gets the JDBC type (java.sql.Types)

for the value stored in col; eg. Value 12 = JDBC VARCHAR, etc.for the value stored in col; eg. Value 12 = JDBC VARCHAR, etc.• getPrecisiongetPrecision(int col): for numbers, gets the mantissa length, for (int col): for numbers, gets the mantissa length, for

others, gets the number of bytes for columnothers, gets the number of bytes for column