JDBC: - Do You Believe That!? - )
JDBC: - Do You Believe That!? - )
JDBC is an alternative to ODBC and ADO that provides database access to programs written in Java. JDBC is not an acronym it doesnt stand for anything!
Do you believe that!? ;-)
DAVID M. KROENKES DATABASE PROCESSING, 10th Edition 2006 Pearson Prentice Hall
14-2
DAVID M. KROENKES DATABASE PROCESSING, 10th Edition 2006 Pearson Prentice Hall
14-3
JDBC Components
DAVID M. KROENKES DATABASE PROCESSING, 10th Edition 2006 Pearson Prentice Hall
14-4
Using JDBC
1a. Load the driver:
The driver class libraries need to be in the CLASSPATH for the Java compiler and for the Java virtual machine. The most reliable way to load the driver into the program is:
Class.forName(string).newInstance();
Compiled queries can be processed via a PreparedStatement object Stored procedures can be processed via a CallableStatement object
9. Release resources
con.close();
Using a PreparedStatement
// Once you have a connection, you can create a // "prepared statement" object. A prepared statement is // precompiled, and can be used repeatedly with new values // for its parameters. // Use question marks for parameter place-holders. PreparedStatement prepStmt = con.prepareStatement( "INSERT INTO Artist (ArtistID, Name, " + "Nationality, BirthDate, DeceasedDate)" + "VALUES (ArtistSeq.nextVal, ?, ?, ?, ? )" ); // Now supply values for the parameters // Parameters are referenced in order starting with 1. prepStmt.setString( 1, "Galvan" ); prepStmt.setString( 2, "French" ); prepStmt.setInt ( 3, 1910 ); prepStmt.setNull ( 4, Types.INTEGER ); // The PreparedStatement object methods: // 1) executeUpdate -- statements that modify the database // 2) executeQuery -- SELECT statements (reads) prepStmt.executeUpdate(); System.out.println( "Prepared statement executed" ); // Now do it again prepStmt.setString( prepStmt.setString( prepStmt.setInt ( prepStmt.setInt (
1, 2, 3, 4,
14-9
14-10
Using ADO.NET
1. Establish a connection to the database:
String connection_string = "Server=(local);UID=sa;PWD=;DATABASE=pubs;Connection Timeout=60"; {Odbc|OleDb|SQL}Connection con = new {Odbc|OleDb|SQL}Connection( connection_string ); Con.Open();
8. End transaction
trans.Commit(); trans.Rollback();
9. Release resources
conn.Close();