Lecture 21 Database Programming and JDBC


Published on

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Lecture 21 Database Programming and JDBC

  1. 1. Lecture 21 Database Programming and JDBC
  2. 2. Database Programming <ul><li>Objective: to access a database from an application program </li></ul><ul><ul><li>As opposed to interactive interfaces like MySQL’s </li></ul></ul><ul><li>Motivation: Interactive interfaces are convenient but </li></ul><ul><ul><li>Not all queries can be expressed in SQL (recursive) </li></ul></ul><ul><li>Impedance mismatch problem (difference between database and programming language models) </li></ul><ul><ul><li>Different data types </li></ul></ul><ul><ul><li>Sets/Multi-sets VS tuple-at-a-time (declarative VS non-declarative/procedural actions) </li></ul></ul><ul><ul><ul><li>E.g. display selected tuples in a GUI </li></ul></ul></ul>
  3. 3. Database Programming Approaches <ul><li>(1) Embedded commands : DB commands are embedded in a general-purpose host programming language </li></ul><ul><ul><li>such as COBOL, C, Java, etc… </li></ul></ul><ul><ul><li>Embedded SQL commands are identified by a special prefix </li></ul></ul><ul><ul><ul><li>E.g. EXEC SQL </li></ul></ul></ul><ul><ul><li>A pre-compiler or a preprocessor first scans the code to identify database statements and extracts them for processing by the DBMS </li></ul></ul><ul><ul><ul><li>Replaced by function calls to the DBMS-generated code </li></ul></ul></ul><ul><ul><ul><li>Static (queries must be known at compile time) </li></ul></ul></ul>
  4. 4. Embedded Commands Example
  5. 5. Database Programming Approaches <ul><li>(2) Library of database functions available to the host language for database calls </li></ul><ul><ul><li>known as an API (Application Programming Interface) </li></ul></ul><ul><ul><li>Host language uses library functions to connect to a database, execute a query, execute an update , etc … </li></ul></ul><ul><ul><li>Database queries/update commands (along with other information) are sent as parameters to function calls </li></ul></ul><ul><ul><ul><li>Dynamic </li></ul></ul></ul><ul><ul><li>E.g. ODBC (Object DataBase Connectivity) and JDBC (used to stand for Java DataBase Connectivity) </li></ul></ul><ul><ul><ul><li>ODBC: SQL Access Group, chiefly Microsoft, in 1992 </li></ul></ul></ul><ul><ul><ul><li>JDBC: Like ODBC but enables SQL function calls for Java programming </li></ul></ul></ul>
  6. 6. Database Programming Approaches <ul><li>Embedded SQL provides static database programming </li></ul><ul><li>API: dynamic database programming </li></ul><ul><ul><li>Advantage: no preprocessor needed (thus more flexible) </li></ul></ul><ul><ul><ul><li>No compile-time restrictions </li></ul></ul></ul><ul><ul><li>Drawback: SQL syntax checks to be done at run-time </li></ul></ul><ul><ul><ul><li>E.g. When executing an SQL statement via ODBC/JDBC, it is not checked for errors until it is run </li></ul></ul></ul>
  7. 7. Java Database Connectivity <ul><li>A Java program with JDBC functions </li></ul><ul><ul><li>can access any relational DBMS that has a JDBC driver (JDBC compliant) </li></ul></ul><ul><ul><ul><li>A JDBC driver is an implementation of the function calls specified in the JDBC API ( java.sql.* ) for a particular RDBMS </li></ul></ul></ul><ul><ul><ul><li>A JDBC driver translates JDBC function calls into DBMS-specific calls that are understood by DBMS and vice-versa </li></ul></ul></ul><ul><ul><li>can connect to several databases known as data sources </li></ul></ul><ul><ul><ul><li>All JDBC drivers loaded (dynamically ) by an application are registered with a driver manager </li></ul></ul></ul><ul><ul><ul><li>Driver manager is responsible to manage different drivers for different DBMSs used within the same program </li></ul></ul></ul>
  8. 8. JDBC Architecture Java Application JDBC Driver manager Driver 3 Driver 2 Driver 1 DBMS DBMS DBMS <ul><ul><li>Application </li></ul></ul><ul><ul><ul><li>-Initiates and terminates connection with a data source </li></ul></ul></ul><ul><ul><ul><li>-Submits SQL statements and retrieves results through the JDBC API </li></ul></ul></ul><ul><ul><li>Driver Manager </li></ul></ul><ul><ul><ul><li>-Loads JDBC driver and passes JDBC function calls from application to correct driver </li></ul></ul></ul><ul><ul><li>Driver(s) </li></ul></ul><ul><ul><ul><li>-Establishes the connection with the data source (thru Driver Manager) </li></ul></ul></ul><ul><ul><ul><li>-Submits requests from and return results to application </li></ul></ul></ul><ul><ul><ul><li>-Translates data and errors from data source format to JDBC standard </li></ul></ul></ul><ul><ul><li>Data source(s) </li></ul></ul><ul><ul><ul><li>-Processes commands from the driver and returns results </li></ul></ul></ul>
  9. 9. The JDBC Steps <ul><li>Importing Packages </li></ul><ul><li>Loading & Registering the JDBC Drivers </li></ul><ul><ul><li>Registers driver with driver manager </li></ul></ul><ul><li>Opening a Connection to a Database </li></ul><ul><ul><li>Also ties driver and DBMS to driver manager </li></ul></ul><ul><li>Creating a Statement Object </li></ul><ul><li>Executing a Query and Returning a Result Set Object </li></ul><ul><li>Processing the Result Set </li></ul><ul><li>Garbage collection </li></ul><ul><ul><li>Closing the Result Set, Statement and Connection Objects </li></ul></ul>
  10. 10. Import JDBC library Load & register JDBC driver Create a connection object Create a statement object Execute SQL statement Process results
  11. 11. Steps in JDBC Database Access <ul><li>(1) Import JDBC library ( import java.sql.* ) </li></ul><ul><ul><li>javax.sql.* (for advanced features, such as scrollable result sets) </li></ul></ul><ul><li>(2) Load & register JDBC driver with manager: </li></ul><ul><ul><li>Class.forName(&quot;com.mysql.jdbc.Driver&quot;); </li></ul></ul><ul><ul><li>This will load the driver and register it with the driver manager in order to make it available to the program </li></ul></ul><ul><ul><li>Can also be done in two steps </li></ul></ul><ul><ul><ul><li>Initializing/loading a driver: (for oracle) driver=new com.mysql.jdbc.Driver() </li></ul></ul></ul><ul><ul><ul><li>Registering it with the DriverManager: DriverManager.registerDriver(driver) </li></ul></ul></ul>
  12. 12. Steps in JDBC Database Access <ul><li>(3) Create a connection object (via getConnection) </li></ul><ul><ul><li>= DriverManager.getConnection(“jdbc:mysql: //<host>: <port>/<db-account>”, <username>, <password>) </li></ul></ul><ul><ul><li>Connection myConnection = DriverManager. getConnection(&quot;jdbc:mysql:// devsrv.cs.csbsju.edu :3306/irahal_compnay&quot;,&quot;irahal&quot;,“****&quot;); </li></ul></ul><ul><li>(4) Create a statement object : </li></ul><ul><ul><li>Statement </li></ul></ul><ul><ul><ul><li>Statement stmt = myConnection.createStatement(); </li></ul></ul></ul><ul><ul><ul><li>String queryString = &quot;Select lname As LastName, fname As FirstName, salary from employee where fname like '%&quot;+ name +&quot;%'&quot;; </li></ul></ul></ul><ul><ul><ul><ul><li>name is a variable of type string </li></ul></ul></ul></ul><ul><ul><li>PreparedStatment (notice the question mark ?) </li></ul></ul><ul><ul><ul><li>String queryString = &quot;Select count(*) as COUNTER from employee where salary> ? &quot;; </li></ul></ul></ul><ul><ul><ul><li>preparedStmt = myConnection.prepareStatement (queryString); </li></ul></ul></ul>
  13. 13. Prepared Statement motivation <ul><li>Why use PreparedStatements: </li></ul><ul><ul><li>“ prepared” = already compiled (querystring is a parameter) </li></ul></ul><ul><ul><li>Used if the same query is to be executed multiple times since it would be compiled only once </li></ul></ul><ul><ul><ul><li>for queries that are executed many times with possibly different contents </li></ul></ul></ul><ul><li>Suppose we would like to run the query </li></ul><ul><ul><li>SELECT * FROM EMPLOYEE WHERE LNAME=‘Moon’; </li></ul></ul><ul><li>But we would like to run this for a number of employees (separately), not only ‘Moon’… </li></ul>
  14. 14. Additional Steps for PreparedStatments in JDBC Database Access <ul><ul><li>(4-1) Identify statement parameters (designated by question marks (?) in the statement string) </li></ul></ul><ul><ul><ul><li>String queryString = &quot;Select count(*) as COUNTER from employee where salary>?&quot;; </li></ul></ul></ul><ul><ul><ul><li>preparedStmt = myConnection.prepareStatement (queryString); </li></ul></ul></ul><ul><ul><li>(4-2) bind parameters to program variables </li></ul></ul><ul><ul><ul><li>pst.setString(1, var1) where pst is a PreparedStatement variable </li></ul></ul></ul><ul><ul><ul><li>preparedStmt.setFloat(1,salary); </li></ul></ul></ul><ul><ul><ul><ul><li>Set 1 st ? in my query to the value of salary which is a float </li></ul></ul></ul></ul>
  15. 15. Connection ResultSet Statement int ExecuteUpdate(String Q) ExecuteQuery(String Q) createStatement() Connection ResultSet Prepared Statement int ExecuteUpdate() ExecuteQuery() prepareStatement (String Q) setString(int num,String val) Statement PreparedStatement
  16. 16. Querying with Prepared Statement String queryStr = &quot; SELECT * FROM EMPLOYEE WHERE FName = ? AND SALARY < ?”; PreparedStatement pstmt = con.prepareStatement(queryStr); pstmt.setString(1, “Joe”); pstmt.setFloat2, 100000); ResultSet rs = pstmt.executeQuery(); 1 st question mark Value to insert
  17. 17. Affecting the DB with PreparedStatement String deleteStr = “ DELETE FROM EMPLOYEE WHERE LNAME = ? and SALARY = ?”; PreparedStatement pstmt = con.prepareStatement(deleteStr); pstmt.setString(1, “RAHAL”); pstmt.setFloat(2, 10000); int delnum = pstmt.executeUpdate();
  18. 18. Create a statement object Identify statement parameters Execute SQL statement
  19. 19. Steps in JDBC Database Access <ul><li>(5) Execute SQL statement (referenced by an object) via JDBC’s </li></ul><ul><ul><li>executeQuery (SELECT statements) </li></ul></ul><ul><ul><ul><li>Returns a ResultSet </li></ul></ul></ul><ul><ul><ul><li>resultset1 = stmt.executeQuery(queryString); (regular statement) </li></ul></ul></ul><ul><ul><ul><li>resultset2 = preparedStmt.executeQuery(); (prepared statement) </li></ul></ul></ul><ul><ul><li>executeUpdate (DDL, INSERT, UPDATE, and DELETE statements) </li></ul></ul><ul><ul><ul><li>Returns how many tuples have been affected (an integer) </li></ul></ul></ul><ul><ul><ul><li>result1 = stmt.executeUpdate(updateString); (regular statement) </li></ul></ul></ul><ul><ul><ul><li>result2 = preparedStmt.executeUpdate(); (prepared statement) </li></ul></ul></ul>
  20. 20. Steps in JDBC Database Access <ul><li>(6) Process query results </li></ul><ul><ul><li>ResultSet is a 2-dimensional table </li></ul></ul><ul><li>Only one ResultSet per Statement can be opened at once </li></ul><ul><li>ResultSet object maintains a cursor pointing to its current row of data </li></ul><ul><li>The 'next' method moves the cursor to the next row </li></ul><ul><li>As of JDBC 2.0, scrollable ResultSets are available, which also include ‘previous’, ’first’, ‘last’, etc.. </li></ul><ul><li>Any methods on the ResultSet will occur on the current row </li></ul>
  21. 21. ResultSet <ul><li>The cursor is positioned before the 1st row upon creation </li></ul><ul><ul><li>Statement stmt=con.createStatement(); </li></ul></ul><ul><ul><li>ResultSet rs = stmt.executeQuery (&quot;SELECT * FROM Table1&quot;); </li></ul></ul><ul><ul><li>while (rs.next()) { //something… } </li></ul></ul>
  22. 22. ResultSet methods <ul><li>Getting the value in some column (for the current row) - depends on attribute data type: </li></ul><ul><ul><li>getString( int columnNum ); </li></ul></ul><ul><ul><li>getString( String columnName ); </li></ul></ul><ul><ul><li>getInt(int columnNum); </li></ul></ul><ul><ul><li>getInt(String columnName); </li></ul></ul><ul><ul><li>Etc… </li></ul></ul><ul><li>To check if null was returned, you have to use wasNull() on the ResultSet after getting the value </li></ul>String s = rs.getString(“column1&quot;);
  23. 23. Mapping Java Types to SQL Types Java method SQL type The driver maps SQL types (varchar, number,…) to the appropriate Java method (getString, getInt…)
  24. 24. Cleaning Up After Yourself <ul><li>(7) Remember to close the Connections, Statements, PreparedStatements and ResultSets in the following order </li></ul>rs.close() stmt.close() pstmt.close() con.close() Highly recommended Recommended Optional (will otherwise be closed by its calling statement)
  25. 25. Timeouts <ul><li>You can use Stmt.setQueryTimeOut(int secs) to set a timeout for the driver to wait for a statement to be completed </li></ul><ul><li>If the operation is not completed in the given time, an SQLException is thrown </li></ul>
  26. 26. Dealing With Exceptions catch (SQLException e) { while (e != null) { //human readable message about the exception System.out.println(e.getMessage()); //String describing the reason of the exception System.out.println(e.getSQLState()); //driver-dependant error code for the exception System.out.println(e.getErrorCode()); e = e.getNextException();}
  27. 27. What will this do? <ul><li>String table1=“create table table1(col1 integer, col2 integer)”; </li></ul><ul><li>Statement st=con.createStatement(); </li></ul><ul><li>int resCreate=st.executeUpdate(table1); </li></ul><ul><li>PreparedStatement ps1 = con.prepareStatement(“insert into Table1 values(?,?)”); </li></ul><ul><li>for(int i=0;i<10;i++){ </li></ul><ul><li>ps1.setInt(1,i); </li></ul><ul><li>ps1.setInt(2,i*i); </li></ul><ul><li>ps1.executeUpdate(); </li></ul><ul><li>} </li></ul><ul><li>Statement st2=con.createStatement(); </li></ul><ul><li>ResultSet rs=executeQuery(“select col2 from Table1”); </li></ul><ul><li>while(rs.next()){ </li></ul><ul><li>System.out.println(rs.getInt(1)); } </li></ul>
  28. 28. Useful JDBC links <ul><li>http://dev.mysql.com/doc/refman/5.0/en/java-connector.html </li></ul><ul><li>http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html </li></ul><ul><li>http://notes.corewebprogramming.com/student/JDBC.pdf </li></ul>