Download presentation
Presentation is loading. Please wait.
Published byCory Harrington Modified over 9 years ago
1
Java: JDBC INE2720 Web Application Software Development Essential Materials
2
All copyrights reserved by C.C. Cheung 2003.2 Outline Overview of JDBC technology Overview of JDBC technology JDBC drivers JDBC drivers JDBC-ODBC Bridge JDBC-ODBC Bridge Seven basic steps in using JDBC Seven basic steps in using JDBC Retrieving data from a ResultSet Retrieving data from a ResultSet Handling SQL exceptions Handling SQL exceptions Summary Summary
3
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.3 JDBC Introduction JDBC provides a standard library for accessing relational databases JDBC provides a standard library for accessing relational databases –API standardizes Way to establish connection to database Way to establish connection to database Approach to initiating queries Approach to initiating queries Method to create stored (parameterized) queries Method to create stored (parameterized) queries The data structure of query result (table) The data structure of query result (table) –Determining the number of columns, etc. –API does not standardize SQL syntax JDBC is not embedded SQL JDBC is not embedded SQL –JDBC class located in java.sql package
4
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.4 Why use JDBC? Ease of programming Ease of programming You can write Java language instead of SQL statements You can write Java language instead of SQL statements Performance improvement Performance improvement Able to rollback to the save set of data Able to rollback to the save set of data Support batch updates Support batch updates Have many optional packages to use Have many optional packages to use
5
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.5 On-line Resources Sun ’ s JDBC Site Sun ’ s JDBC Site –http://java.sun.com/products/jdbc/ JDBC Tutorial JDBC Tutorial –http://java.sun.com/docs/books/tutorial/jdbc/ List of Available JDBC Drivers List of Available JDBC Drivers –http://industry.java.sun.com/products/jdbc/drivers/ API for java.sql API for java.sql –http://java.sun.com/j2se/1.3/docs/api/java/sql/ package-summary.html
6
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.6 JDBC Drivers JDBC consists of two parts: JDBC consists of two parts: –JDBC API, a purely Java-based API –JDBC Driver Manager,which communicates with vendor-specific drivers that perform the real communication with the database. –Point: translation to vendor format is performed on the client –No changes needed to server –Driver (translator) needed on client
7
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.7 JDBC-ODBC Bridge ODBC (Open DataBase Connectivity) ODBC (Open DataBase Connectivity) –A set of APIs for Database access –Originally, designed for windows platforms –Now, it extends to non-windows platforms –Using C interfaces More information: More information: –http://www.microsoft.com/data/odbc/default.htm
8
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.8 Seven Basic Steps in Using JDBC 1. Load the driver 2. Define the Connection URL 3. Establish the Connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection
9
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.9 JDBC: Details of Process 1. Load the driver try { try { Class.forName("connect.microsoft.MicrosoftDriver"); Class.forName("connect.microsoft.MicrosoftDriver"); Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("oracle.jdbc.driver.OracleDriver"); } catch { ClassNotFoundException cnfe) { } catch { ClassNotFoundException cnfe) { System.out.println("Error loading driver: " cnfe); System.out.println("Error loading driver: " cnfe); } 2. Define the Connection URL String host = "dbhost.yourcompany.com"; String host = "dbhost.yourcompany.com"; String dbName = "someName"; String dbName = "someName"; int port = 1234; int port = 1234; String oracleURL = "jdbc:oracle:thin:@" + host + String oracleURL = "jdbc:oracle:thin:@" + host + ":" + port + ":" + dbName; ":" + port + ":" + dbName; String sybaseURL = "jdbc:sybase:Tds:" + host + String sybaseURL = "jdbc:sybase:Tds:" + host + ":" + port + ":" + "?SERVICENAME=" + dbName; ":" + port + ":" + "?SERVICENAME=" + dbName;
10
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.10 JDBC: Details of Process, cont. 3. Establish the Connection String username = "jay_debesee"; String password = "secret"; Connection connection = DriverManager.getConnection(oracleURL, username, password); username, password); 4. Create a Statement Statement statement = connection.createStatement();
11
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.11 JDBC: Details of Process, cont. 5. Execute a Query String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query); –To modify the database, use executeUpdate, supplying a string that uses UPDATE, INSERT, or DELETE –Use setQueryTimeout to specify a maximum delay to wait for results
12
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.12 JDBC: Details of Process, cont. 6. Process the Result while(resultSet.next()) { System.out.println(resultSet.getString(1) + " " + System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString(2) + " " + resultSet.getString(3)); resultSet.getString(3)); } –First column has index 1, not 0 –ResultSet provides various getXxx methods that take a column index or name and returns the data 7. Close the Connection connection.close(); connection.close(); –As opening a connection is expensive, postpone this step if additional database operations are expected
13
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.13 import java.sql.*; public class TestDB { public static void main(String[] args) { public static void main(String[] args) { // Use driver from Connect SW. // Use driver from Connect SW. String driver = "connect.microsoft.MicrosoftDriver"; String driver = "connect.microsoft.MicrosoftDriver"; try { try { Class.forName(driver); Class.forName(driver); String url = "jdbc:ff-microsoft://" + // FastForward String url = "jdbc:ff-microsoft://" + // FastForward "dbtest.apl.jhu.edu:1433/" + // Host:port "dbtest.apl.jhu.edu:1433/" + // Host:port "pubs"; // Database name "pubs"; // Database name String user = "sa", password=""; String user = "sa", password=""; Connection connection = Connection connection = DriverManager.getConnection(url, user, password); DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); Statement statement = connection.createStatement(); String query = String query = "SELECT col1, col2, col3 FROM testDB"; "SELECT col1, col2, col3 FROM testDB"; // Execute query and save results. // Execute query and save results. ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query); Basic JDBC Example
14
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.14 // Print column names. // Print column names. String divider = "-----+------+-----"; String divider = "-----+------+-----"; System.out.println("Col1 | Col2 | Col3\n" + divider); System.out.println("Col1 | Col2 | Col3\n" + divider); // Print results // Print results while(results.next()) { while(results.next()) { System.out.println System.out.println (pad(results.getString(1), 4) + " | " + (pad(results.getString(1), 4) + " | " + pad(results.getString(2), 4) + " | " + pad(results.getString(2), 4) + " | " + results.getString(3) + "\n" + divider); results.getString(3) + "\n" + divider); } connection.close(); connection.close(); } catch(ClassNotFoundException cnfe) { } catch(ClassNotFoundException cnfe) { System.out.println("No such class: " + driver); System.out.println("No such class: " + driver); } catch(SQLException se) { } catch(SQLException se) { System.out.println("SQLException: " + se); System.out.println("SQLException: " + se); } }... }... Basic JDBC Example, cont.
15
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.15 Microsoft Access Example Northwind sample database Northwind sample database Northwind.mdb located in C:\Program Files\Microsoft Office\Office\Samples
16
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.16 MS Access Example: Create a data source Create System (Data Source Name) DSN through ODBC data source Create System (Data Source Name) DSN through ODBC data source
17
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.17 MS Access Example: Java Code import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class NorthwindServlet extends HttpServlet { public static void main(String[] args) { public static void main(String[] args) { System.out.println(doQuery()); System.out.println(doQuery()); } public void doGet(HttpServletRequest request, public void doGet(HttpServletRequest request, HttpServletResponse response) HttpServletResponse response) throws ServletException, IOException { throws ServletException, IOException { PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter(); out.println(doQuery()); out.println(doQuery()); }... }...}
18
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.18 public static String doQuery() { public static String doQuery() { StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer(); try { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connection = Connection connection = DriverManager.getConnection("jdbc:odbc:Northwind","",""); DriverManager.getConnection("jdbc:odbc:Northwind","",""); Statement statement = connection.createStatement(); Statement statement = connection.createStatement(); String query = "SELECT FirstName, LastName FROM Employees"; String query = "SELECT FirstName, LastName FROM Employees"; ResultSet result = statement.executeQuery(query); ResultSet result = statement.executeQuery(query); buffer.append("Northwind Database\n\n"); buffer.append("Northwind Database\n\n"); while (result.next()) { while (result.next()) { buffer.append(result.getString(1) + " " + buffer.append(result.getString(1) + " " + result.getString(2) + "\n"); result.getString(2) + "\n"); } connection.close(); connection.close(); } catch (ClassNotFoundException cnfe) { } catch (ClassNotFoundException cnfe) { buffer.append("Couldn't find class file" + cnfe); buffer.append("Couldn't find class file" + cnfe); } catch (SQLException sqle) { } catch (SQLException sqle) { buffer.append("SQL Exception: " + sqle); buffer.append("SQL Exception: " + sqle); } return buffer.toString(); return buffer.toString(); } MS Access Example (Continued)
19
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.19 MS Access Example, Result
20
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.20 MySQL & Connector/J
21
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.21 ResultSet Overview Overview –A ResultSet contains the results of the SQL query Represented by a table with rows and columns Represented by a table with rows and columns In JDBC 1.0 you can only proceed forward through the rows using next In JDBC 1.0 you can only proceed forward through the rows using next Useful Methods Useful Methods All methods can throw a SQLException All methods can throw a SQLException –close Releases the JDBC and database resources Releases the JDBC and database resources The result set is automatically closed when the associated Statement object executes a new query The result set is automatically closed when the associated Statement object executes a new query
22
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.22 ResultSet (Continued) Useful Methods Useful Methods –getMetaDataObject Returns a ResultSetMetaData object containing information about the columns in the ResultSet Returns a ResultSetMetaData object containing information about the columns in the ResultSet –next Attempts to move to the next row in the ResultSet Attempts to move to the next row in the ResultSet –If successful true is returned; otherwise, false –The first call to next positions the cursor a the first row –Calling next clears the SQLWarning chain –getWarnings Returns the first SQLWarning or null if no warnings occurred Returns the first SQLWarning or null if no warnings occurred
23
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.23 ResultSet (Continued) Useful Methods Useful Methods –findColumn Returns the corresponding integer value corresponding to the specified column name Returns the corresponding integer value corresponding to the specified column name Column numbers in the result set do not necessarily map to the same column numbers in the database Column numbers in the result set do not necessarily map to the same column numbers in the database –getXxx Returns the value from the column specified by column name or column index as an Xxx Java type Returns the value from the column specified by column name or column index as an Xxx Java type Returns 0 or null, if the value is a SQL NULL Returns 0 or null, if the value is a SQL NULL Legal getXxx types: Legal getXxx types: –wasNull Used to check if the last getXxx read was a SQL NULL Used to check if the last getXxx read was a SQL NULL double byte int Date String float short long Time Object
24
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.24 Using Statement Overview Overview –Through the Statement object, SQL statements are sent to the database. –Two types of statement objects are available: Statement Statement –for executing a simple SQL statements PreparedStatement PreparedStatement –for executing a precompiled SQL statement passing in parameters
25
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.25 Useful Statement Methods executeQuery executeQuery –Executes the SQL query and returns the data in a table (ResultSet) –The resulting table may be empty but never null ResultSet results = statement.executeQuery("SELECT a, b FROM table"); executeUpdate executeUpdate –Used to execute for INSERT, UPDATE, or DELETE SQL statements –The return is the number of rows that were affected in the database –Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE and ALTER TABLE int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" + "WHERE STATUS=0"); "WHERE STATUS=0");
26
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.26 Useful Statement Methods (Continued) execute execute –Generic method for executing stored procedures and prepared statements –Rarely used (for multiple return result sets) –The statement execution may or may not return a ResultSet (use statement.getResultSet). If the return value is true, two or more result sets were produced getMaxRows/setMaxRows getMaxRows/setMaxRows –Determines the number of rows a ResultSet may contain –Unless explicitly set, the number of rows are unlimited getQueryTimeout/setQueryTimeout getQueryTimeout/setQueryTimeout –Specifies the amount of a time a driver will wait for a STATEMENT to complete before throwing a SQLException
27
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.27 Prepared Statements (Precompiled Queries) Idea Idea –If you are going to execute similar SQL statements multiple times, using “ prepared ” (parameterized) statements can be more efficient –Create a statement in standard form that is sent to the database for compilation before actually being used –Each time you use it, you simply replace some of the marked parameters using the setXxx methods As PreparedStatement inherits from Statement the corresponding execute methods have no parameters As PreparedStatement inherits from Statement the corresponding execute methods have no parameters –execute() –executeQuery() –executeUpdate()
28
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.28 Prepared Statement, Example Connection connection = DriverManager.getConnection(url, user, password); DriverManager.getConnection(url, user, password); PreparedStatement statement = connection.prepareStatement("UPDATE employees " + connection.prepareStatement("UPDATE employees " + "SET salary = ? " + "SET salary = ? " + "WHERE id = ?"); "WHERE id = ?"); int[] newSalaries = getSalaries(); int[] employeeIDs = getIDs(); for(int i=0; i<employeeIDs.length; i++) { statement.setInt(1, newSalaries[i]); statement.setInt(1, newSalaries[i]); statement.setInt(2, employeeIDs[i]); statement.setInt(2, employeeIDs[i]); statement.executeUpdate(); statement.executeUpdate();}
29
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.29 Useful Prepared Statement Methods setXxx setXxx –Sets the indicated parameter (?) in the SQL statement to the value clearParameters clearParameters –Clears all set parameter values in the statement Handling Servlet Data Handling Servlet Data –Query data obtained from a user through an HTML form may have SQL or special characters that may require escape sequences –To handle the special characters, pass the string to the PreparedStatement setString method which will automatically escape the string as necessary
30
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.30 Exception Handling SQL Exceptions SQL Exceptions –Nearly every JDBC method can throw a SQLException in response to a data access error –If more than one error occurs, they are chained together –SQL exceptions contain: Description of the error, getMessage Description of the error, getMessage The SQLState (Open Group SQL specification) identifying the exception, getSQLState The SQLState (Open Group SQL specification) identifying the exception, getSQLState A vendor-specific integer, error code, getErrorCode A vendor-specific integer, error code, getErrorCode A chain to the next SQLException, getNextException A chain to the next SQLException, getNextException
31
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.31 SQL Exception Example try {... // JDBC statement. } catch (SQLException sqle) { while (sqle != null) { while (sqle != null) { System.out.println("Message: " + sqle.getMessage()); System.out.println("Message: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLState: " + 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.getNextException(); sqle = sqle.getNextException(); }} –Don ’ t make assumptions about the state of a transaction after an exception occurs –The safest best is to attempt a rollback to return to the initial state
32
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.32 SQL Warnings SQLWarnings are rare, but provide information about the database access warnings SQLWarnings are rare, but provide information about the database access warnings Chained to object whose method produced the warning Chained to object whose method produced the warning The following objects can receive a warning: The following objects can receive a warning: –Connection –Statement –ResultSet Call getWarning to obtain the warning object, and getNextWarning (on the warning object) for any additional warnings Call getWarning to obtain the warning object, and getNextWarning (on the warning object) for any additional warnings Warnings are cleared on the object each time the statement is executed Warnings are cleared on the object each time the statement is executed
33
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.33 SQL Warning, Example ResultSet results = statement.executeQuery(someQuery); SQLWarning warning = statement.getWarnings(); while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.println("SQLState: " + warning.getSQLState()); System.out.println("Vendor Error: " + warning.getErrorCode()); System.out.println("Vendor Error: " + warning.getErrorCode()); warning = warning.getNextWarning(); warning = warning.getNextWarning();} while (results.next()) { int value = rs.getInt(1); int value = rs.getInt(1);... // Call additonal methods on result set.... // Call additonal methods on result set. SQLWarning warning = results.getWarnings(); SQLWarning warning = results.getWarnings(); while (warning != null) { while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.println("SQLState: " + warning.getSQLState()); System.out.println("Vendor Error: " + warning.getErrorCode()); System.out.println("Vendor Error: " + warning.getErrorCode()); warning = warning.getNextWarning(); warning = warning.getNextWarning(); } }
34
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.34 Summary In JDBC 1.0, can only step forward ( next ) through the ResultSet In JDBC 1.0, can only step forward ( next ) through the ResultSet Be sure to handle the situation where getXxx returns a NULL Be sure to handle the situation where getXxx returns a NULL Understand the relationship between: Understand the relationship between: –Connection object –Statement object –ResultSet object Be default, a connection is auto-commit Be default, a connection is auto-commit SQL Exceptions and Warnings are chained together SQL Exceptions and Warnings are chained together
35
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.35 References CWP2: Chapter 22 CWP2: Chapter 22 http://java.sun.com/products/jdbc/ http://java.sun.com/products/jdbc/ http://java.sun.com/products/jdbc/ http://java.sun.com/docs/books/tutorial/jdbc/ http://java.sun.com/docs/books/tutorial/jdbc/ http://java.sun.com/docs/books/tutorial/jdbc/ http://industry.java.sun.com/products/jdbc/drivers http://industry.java.sun.com/products/jdbc/drivers http://industry.java.sun.com/products/jdbc/drivers http://www.mysql.com/ http://www.mysql.com/ http://www.mysql.com/ The End. The End. Thank you for patience! Thank you for patience!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.