What is JDBC? J • JDBC is: Java Database Connectivity – is i a Java J API for f connecting ti programs written itt in i Java J to t the data in relational databases. – consists of a set of classes and interfaces written in the Java programming language. – is used for accessing databases from Java applications. • JDBC: – – – – establishes a connection with a database sends SQL statements processes the results sends back the results. 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 is used by Java programmers to connect to databases • With a small "bridge" program, you can use the JDBC iinterface f to access ODBC ODBC--accessible ibl databases. • Open Database Connectivity (ODBC ODBC)) provides a standard software API method for using database management systems (DBMS). (DBMS) The designers of ODBC aimed to make it independent of programming languages languages, database systems, and operating systems. JDBC API • The JDBC API supports both twotwo-tier and three--tier models for database access. three • Two Two--tier model -- a Java applet or application interacts directly with the database. • Three Three--tier model -- introduces a middle middle--level server for execution of business logic: – the middle tier to maintain control over data access. JDBC Drivers • • • • Type I: “JDBC“JDBC JDBC-ODBC bridge driver driver” Type II: “Native“Native-API partly Java driver” T Type III: III “JDBC“JDBC-Net N pure JJava ddriver” i ” Type IV: “Native protocol pure Java driver” JDBC Architectures Java Application JDBC driver manager g JDBC/ODBC bridge JDBC/native bridge ODBC Driver Native driver (DBMS specific) JDBC middleware JDBC Driver (various DBMS) (DBMS Specific) DBMS JDBC Class Usage DriverManager Driver Connection Statement ResultSet The JDBC Steps 1. Importing Packages 2. Registering the JDBC Drivers 3 Opening a Connection to a Database 3. 4. Creating a Statement Object 5 Executing 5. E i a Query Q andd Returning R i aR Result l Set S Object 6 Processing 6. P i the h Result R l Set S 7. Closing the Statement Object 8. Closing the Connection 1) Importing Packages import java.sql.*; 2) Registering the driver Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); OR Driver d=new sun.jdbc.odbc.JdbcOdbcDriver(); jdb db db Odb D i () g g ( ); DriverManager.registerDriver(d); 3)) Connecting g to DataBase Connection con = DriverManager.getConnection DriverManager getConnection (jdbc:odbc:datasourcename, ”username”, ”password”); 4) Create a statement object Statement stmt=con.createStatement(); 5) Executing a Query and returning a ResultSet object ResultSet rs rs= stmt.executeQuery ( “SELECT * from authors”); 6) Close the statement and the connection stmt.close(); con close(); con.close(); Statement Methods ResultSet executeQuery(String) – Execute a SQL statement that returns a single ResultSet. i t executeUpdate(String) int t U d t (St i ) – Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) – Execute a SQL Q statement and returns a boolean value. ResultSet • A ResultSet provides access to a table of data generated db by executing i aS Statement. • Only one ResultSet per Statement can be open at once. • The table rows are retrieved in sequence. q • A ResultSet maintains a cursor pointing to its current row of data. • The 'next' method moves the cursor to the next row. row – you can’t rewind while(rs.next()) { System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3)); g g( )); } First column has index 11, not 0 – The ResultSet provides getXxx methods that take a column index or column name and returns the data – Can also access result meta data (column names, etc.) ResultSet Methods • Type getType(int columnIndex) – returns t the th given i field fi ld as th the given i type • Type getType(String columnName) – same, same but uses name of field – less efficient A Simple JDBC application loadDriver getConnection createStatement execute(SQL) Result handling yes More M results no closeStatment closeConnection import java.sql.*; public bli class l jdb jdbctest t t{ public static void main(String args[]){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection ((“jdbc:odbc:mydatasource", jdbc:odbc:mydatasource , "user", user , "passwd"); passwd ); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery (" l t name, number ("select b ffrom pcmtable t bl where h number b < 2"); while(rs.next()) System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")"); stmt.close() con.close(); } catch(Exception e){ }}} Scrollable ResultSet St t Statement t createStatement( t St t t( resultSetType, ltS tT resultSetConcurrency) ltS tC ) • resultSetType resultSetType:: • ResultSet.TYPE_FORWARD_ONLY R l S TYPE FORWARD ONLY -allows only forward movement of the cursor • ResultSet.TYPE_SCROLL_INSENSITIVE R l S TYPE SCROLL INSENSITIVE -backwards, forwards, random cursor movement. -does d nott reflect r fl t the th changes h in i the th data. d t • ResultSetTYPE_SCROLL_SENSITIVE -backwards, backwards forwards forwards, random cursor movement movement. - reflect the changes in the data. Scrollable ResultSet (cont’d) • resultSetConcurrency: • ResultSet.CONCUR_READ_ONLY ResultSet.CONCUR READ ONLY This is the default and allows only data to be read from the database. • ResultSet.CONCUR_UPDATABLE This option allows to make changes to the database based on new methods and positioning ability of the cursor. • Example: Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); R ResultSet ltS t rs= stmt.executeQuery(str); t t t Q ( t ) public boolean absolute(int row) throws SQLException • -If the given row number is positive, this method moves the cursor to the given row number (with the first row numbered 1). • -If the row number is negative, the cursor moves to a relative position from the last row. • -If the row number b is 0, an SQLException will b be raised. d public bli b boolean l relative(int l ti (i t row) ) th throws SQLException • Shifts the control of a result set cursor, cursor forward or backward, backward relative to the row number that you specify as a parameter. This method accepts either a positive or negative value as a parameter. Scrollable ResultSet (cont’d) public boolean first() public boolean last() public boolean previous() public boolean next() p () public void beforeFirst() public p void afterLast() () public boolean isFirst() public boolean isLast() p public boolean isAfterLast() public boolean isBeforeFirst() public int getRow() Updatable ResultSet • • • • • void updateRow() void insertRow() void id ddeleteRow() l R () void updateString() void updateInt() About Prepared Statements • Allows you to pass runtime parameters to the SQL statements to query and modify the data in a table table. • Also used for queries that are executed many times. p and p prepared p onlyy once byy JJDBC. • Complied • Helps in reducing the load on the database server and thus improving the performance of the application application. • Instead of values, use ‘? ‘?’. • Hence, Prepared Statements can be thought of as statements that contain placeholders to be substituted later with actual values. Querying with PreparedStatement P dSt t t String str = "SELECT * FROM employee " + "WHERE emp_id= ? and salary > ?"; PreparedStatement ps = con.prepareStatement(str); p p ( ); ps.setString(1, "34562"); ps.setInt(2, 26000); R ResultSet ltS t rs = ps.executeQuery(); t Q () Updating with PreparedStatement String str = “DELETE FROM employee l "+ "WHERE emp_id = ? and salary > ?"; PreparedStatement ps = con.prepareStatement(str); ps.setString(1, "34562"); ps.setDouble(2, 26000); int count = ps.executeUpdate(); Statements vs. P PreparedStatements dS • Are these the same? What do they do? String val = "abc"; PreparedStatement ps = con.prepareStatement("select * from R where A=?"); ps.setString(1, p g( val); ) ResultSet rs = pstmt.executeQuery(); String val = "abc"; abc ; Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery("select * from R where A=" + val); Statements vs. P PreparedStatements dS • Will this work? PreparedStatement ps = con prepareStatement("select con.prepareStatement( select * from ?"); ? ); ps.setString(1, myFavoriteTableString); • No!!! A ‘?’ can onlyy be used to represent p a column value Transactions and JDBC • Transaction: more than one statement that must all succeed (or all fail) together – e.g., updating several tables due to customer purchase • If one fails, the system must reverse all previous actions • Also can’t leave DB in inconsistent state halfway through a transaction • COMMIT = complete transaction • ROLLBACK = cancel all actions Example • Suppose we want to transfer money from bank account 13 to account 72: PreparedStatement ps = con.prepareStatement("update BankAccount sett amountt = amountt + ? where accountId = ?"); ps setInt(1 -100); ps.setInt(1,-100); ps.setInt(2, 13); p ps.executeUpdate(); p (); What happens if this ps.setInt(1, 100); update fails? ps.setInt(2, 72); ps.executeUpdate(); Transaction Management • Transactions are not explicitly opened and closed • The connection has a state called AutoCommit mode d • if AutoCommit is true true,, then every statement is automatically committed • if AutoCommit is false false,, then everyy statement is added to an ongoing transaction • Default: true AutoCommit setAutoCommit(boolean ( val)) • If you set AutoCommit to false, you must explicitly commit or rollback the transaction using con.commit() and con.rollback() • Note: DDL statements (e.g., creating/deleting tables) in a transaction may be ignored or may cause a commit to occur Save Points Statement st st=con con.createStatement( createStatement( ); st.executeUpdate(str1); S Savepoint i svpt=con.setSavepoint( S i ( )); st.executeUpdate(str2); if(…) conn.rollback(svpt); …. con.commit( ); Batch Updates • A batch is a group of update statements that are sent to a database to be executed as a single unit. • You can send the batch to a database in a single g request using the same Connection object. pp and • Reduces network calls between the application the database. • Disable the autoauto-commit mode so that you can rollback the transaction. Batch Updates con.setAutoCommit(false); Statement stmt=con.createStatement( ); stmt.addBatch(“INSERT ( INTO p product (p_id, p_desc) VALUES (1001,’Printer ’ ) ” ); stmt.addBatch(“INSERT stmt.addBatch( INSERT INTO product (p_id, p_desc) VALUES (1002,’Scanner’ ) ” ); int[ ] count=stmt.executeBatch( ) ; Metadata • It gives the information about the data such as structure and properties of the table. • JDBC API provides the following two metadata interfaces to retrieve the information about the data base and result set ¾ DatabaseMetaData D b M D iinterface f ¾ ResultSetMetaData interface DatabaseMetaData • Provides the methods that enable you to determine the properties of a database. • Provides information such as: ¾ Names of database tables ¾ Database version • Use the following method call to create an object of the DatabaseMetaData interface: DatabaseMetaData dbmd=con.getMetaData( ); Methods of DatabaseMetaData • String g getDriverName( g () Retrieves the name of the JDBC driver g getDriverVersion( g () • String Retrieves the version of the JDBC driver • String getURL( ) Retrieves the URL of the database. • boolean isReadOnly( ) Indicates whether the database is read only database ResultSet MetaData •A ResultSetMetaData is an object that can be used to get information about the properties of the columns in a ResultSet object. •Provides information such as: ¾ Number of columns ¾ Names of columns ¾ Data types of the columns •ResultSetMetaData rsmd=rs.getMetaData( g ( ); Methods of ResultSetMetaData • • • • • • int getColumnCount( ) String getColumnName(int column_index) S i getTableName(int String T bl N (i column_index) l i d ) int getColumnType(int column_index) boolean isCaseSensitive(int column_index) boolean isReadOnly(int column column_index) index) Row Sets • RowSet interface extends the ResultSet interface. • Row sets don’t have to be tied to a database connection. • Some of the interfaces that extend the RowSet interface: ¾ CachedRowSet ¾ WebRowSet ¾ FilteredRowSet and JoinRowSet ¾ JdbcRowSet Jdb R S Cached Row Sets • Contains all data from a result set. • Each user command simply opens the database connection, issues a query ,puts the result in a row set and then closes the database connection. • You can also modify the data in a cached row set. • You need to make an explicit request to accept the accumulated changes. • Not appropriate for large query results. • ResultSet rs=stmt.executeQuery(str); CachedRowSet rowset=new com.sun.rowset.CachedRowSetImpl( C h dR S I l( )); rowset.populate(rs); con.close( l ( )); • rowset.acceptChanges(con); OR • rowset.setURL(“….”); rowset setUsername(“…”); rowset.setUsername( ); rowset.setPassword(“……”); rowset.setcommand(“SELECT rowset.setcommand( SELECT * FROM Books Books”); ); rowset.execute( ); • rowset.acceptChanges( ); JDBC Class Diagram