Documente Academic
Documente Profesional
Documente Cultură
globsyn technologies
Learning objectives
Connect to a database using JDBC and perform a simple query. Update relational data using JDBC to execute updates, inserts and deletes. Use prepared statements to produce reusable database queries and optimize execution time. Use callable statements to access database procedures. Use scrollable and updatable results sets for more robust solutions. Use commit and rollback to build transactional systems. Use batch processing for efficient handling of large datasets.
JDBC
JDBC (Java Database Connectivity) API allows Java programs to connect to databases. Database access is the same for all database vendors. The JVM uses a JDBC driver to translate generalized JDBC calls into vendor specific database calls.
JDBC Architecture
Application JDBC Driver
Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code
JDBC Drivers
Type I: Bridge Type II: Native Type III: Middleware Type IV: Pure
JDBC Drivers
Type I Bridge
ODBC
ODBC Driver
DB
JDBC
Type II Native
CLI (.lib)
DB
Middleware Server
DB
Type IV Pure
DB
Cons
The vendor database library needs to be loaded on each client machine. Consequently, type 2 drivers cannot be used for the Internet. Type 2 drivers show lower performance than type 3 and type 4 drivers.
Cons
Type 3 drivers require database-specific coding to be done in the middle tier. Additionally, traversing the recordset may take longer, since the data comes through the backend server.
Cons
With type 4 drivers, the user needs a different driver for each database.
Type I Driver
Requires installation/configuration on client machines Not good for Web e.g. ODBC Bridge
Type II Driver
Native API drivers Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers
Type IV Driver
100% Pure Java Use Java networking libraries to talk directly to database engines Only disadvantage: need to download a new driver for each database engine e.g. Oracle, mSQL
java.sql
JDBC is implemented via classes in the java.sql package
JDBC API
DriverManager
Loads, chooses drivers
Connection
a series of SQL statements to and from the DB
Statement
a single SQL statement
ResultSet
the records returned from a Statement
DriverManager
Connection getConnection (String url, String user, String password) Connects to given JDBC URL with given user name and password. Throws java.sql.SQLException. Returns a Connection object.
Connection
A Connection represents a session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned. Can have multiple connections to a database. Also provides metadata -- information about the database, tables, and fields. Also methods to deal with transactions.
Obtaining a Connection
try { Class.forName (Driver"); Connection con = DriverManager.getConnection(DBURL,username ,password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
Connection Methods
Statement createStatement()
Statement
A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
Statement Methods
ResultSet executeQuery(String)
Execute a SQL statement that returns a single ResultSet.
int executeUpdate(String)
Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed.
ResultSet
A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row.
you cant rewind in JDBC 1.0 In JDBC 2.0 it is supported
ResultSet Methods
boolean next()
activates the next row the first call to next() activates the first row returns false if there are no more rows
void close()
disposes of the ResultSet allows you to re-use the Statement that created it
ResultSet Methods
Type getType(int columnIndex)
returns the given field as the given type fields indexed starting at 1 (not 0)
ResultSet Methods
String getString(int columnIndex) boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex)
Connection
Statement
ResultSet
MySQL
com.mysql.jdbc.Driver
Configuring Driver
Download the driver jar file in a directory. Set the path of the directory in the CLASSPATH environment variable.
Connection URL
Oracle
jdbc:oracle:thin:@localhost:1521:orcl
MySQL
jdbc:mysql://localhost:3306/gps
import java.sql.*; public class jdbctest { public static void main(String args[]){ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl", scott", tiger"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("select name, number from emp where ecode> 2"); while(rs.next()) System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")"); stmt.close() con.close(); } catch(Exception e){ System.err.println(e); }}}
isNull
In SQL, NULL means the field is empty Not the same as 0 or In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)
Transaction Management
The connection has a state called AutoCommit mode. If AutoCommit is true, then every statement is automatically committed. Default case: true
setAutoCommit
con.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using con.commit() and con.rollback()
Batch update
statement = connection.createStatement(); String update1 = "UPDATE employees SET email = 'a@a.com' WHE RE email = 'a@b.com'"; statement.addBatch(update1); String update2 = "UPDATE employees SET email = 'b@b.com' WHE RE email = 'b@c.com'"; statement.addBatch(update2); String update3 = "UPDATE employees SET email = 'c@c.com' WHER E email = 'c@d.com'"; statement.addBatch(update3); statement.executeBatch();
ResultSetMetadata
ResultSet rs = stmt.executeQuery("select * from EMP"); ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount(); for (int i = 1; i <= numberOfColumns; i++) { String colName = rsmd.getColumnName(i); String tableName = rsmd.getTableName(i); String name = rsmd.getColumnTypeName(i); boolean caseSen = rsmd.isCaseSensitive(i); boolean writable = rsmd.isWritable(i); System.out.println(colName+ +tableName+ +name+ +caseSen + + writable);
}
Scrollability, positioning, and sensitivity are determined by the result set type.
ResultSet.CONCUR_READ_ONLY ResultSet.CONCUR_UPDATABLE
Example
try { con = DriverManager.getConnection(url, user, pass); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery("SELECT * FROM Users where nick=\"ian\""); // Get the resultset ready, update the passwd field, commit rs.first(); rs.updateString("password", "unguessable"); rs.updateRow(); rs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); }