java: jdbc ine2720 web application software development essential materials

35
Java: JDBC Java: JDBC INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

Upload: cory-harrington

Post on 27-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java: JDBC INE2720 Web Application Software Development Essential Materials

Java: JDBCJava: JDBC

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

Page 2: Java: JDBC INE2720 Web Application Software Development Essential Materials

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

OutlineOutline

Overview of JDBC technologyOverview of JDBC technology JDBC driversJDBC drivers JDBC-ODBC BridgeJDBC-ODBC Bridge Seven basic steps in using JDBCSeven basic steps in using JDBC Retrieving data from a ResultSetRetrieving data from a ResultSet Handling SQL exceptionsHandling SQL exceptions SummarySummary

Page 3: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

JDBC IntroductionJDBC Introduction

JDBC provides a standard library for JDBC provides a standard library for accessing relational databasesaccessing relational databases– API standardizesAPI standardizes

Way to establish connection to databaseWay to establish connection to database Approach to initiating queries Approach to initiating queries Method to create stored (parameterized) queriesMethod 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.Determining the number of columns, etc.

– API does not standardize SQL syntaxAPI does not standardize SQL syntax JDBC is not embedded SQLJDBC is not embedded SQL

– JDBC class located in JDBC class located in java.sqljava.sql package package

Page 4: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

Why use JDBC?Why use JDBC?

Ease of programmingEase of programming You can write Java language instead You can write Java language instead

of SQL statementsof SQL statements Performance improvementPerformance improvement Able to rollback to the save set of Able to rollback to the save set of

datadata Support batch updatesSupport batch updates Have many optional packages to useHave many optional packages to use

Page 5: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

On-line ResourcesOn-line Resources

Sun’s JDBC SiteSun’s JDBC Site– http://java.sun.com/products/jdbc/http://java.sun.com/products/jdbc/

JDBC TutorialJDBC Tutorial– http://java.sun.com/docs/books/tutorial/jdbc/http://java.sun.com/docs/books/tutorial/jdbc/

List of Available JDBC DriversList of Available JDBC Drivers– http://industry.java.sun.com/products/jdbc/http://industry.java.sun.com/products/jdbc/

drivers/drivers/ API for java.sqlAPI for java.sql

– http://java.sun.com/j2se/1.3/docs/api/java/sql/http://java.sun.com/j2se/1.3/docs/api/java/sql/package-summary.htmlpackage-summary.html

Page 6: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

JDBC DriversJDBC Drivers

JDBC consists of two parts: JDBC consists of two parts: – JDBC API, a purely JDBC API, a purely

Java-based API Java-based API – JDBC Driver Manager,which JDBC Driver Manager,which

communicates with communicates with vendor-specific drivers that vendor-specific drivers that perform the real perform the real communicationcommunicationwith the database. with the database.

– Point: translation to vendorPoint: translation to vendorformat is performed onformat is performed onthe clientthe client

– No changes needed to serverNo changes needed to server– Driver (translator) neededDriver (translator) needed

on clienton client Database

JDBC Driver Manager

Java Application

JDBC API

JDBC Driver API

Vendor Specific JDBC Driver

Vendor SpecificODBC Driver

JDBC-ODBCBridge

Database

Page 7: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

JDBC-ODBC BridgeJDBC-ODBC Bridge

ODBC (Open DataBase Connectivity)ODBC (Open DataBase Connectivity)

–A set of APIs for Database accessA set of APIs for Database access

–Originally, designed for windows Originally, designed for windows platformsplatforms

–Now, it extends to non-windows Now, it extends to non-windows platformsplatforms

–Using C interfacesUsing C interfaces

More information:More information:–http://www.microsoft.com/data/odbc/default.htmhttp://www.microsoft.com/data/odbc/default.htm

Page 8: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88

Seven Basic Steps in Seven Basic Steps in Using JDBCUsing JDBC

1.1. Load the driverLoad the driver

2.2. Define the Connection URLDefine the Connection URL

3.3. Establish the ConnectionEstablish the Connection

4.4. Create a Statement objectCreate a Statement object

5.5. Execute a queryExecute a query

6.6. Process the resultsProcess the results

7.7. Close the connectionClose the connection

Page 9: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

JDBC: Details of JDBC: Details of ProcessProcess1.1. Load the driverLoad the driver try {try { Class.forNameClass.forName("connect.microsoft.MicrosoftDriver");("connect.microsoft.MicrosoftDriver"); Class.forNameClass.forName("oracle.jdbc.driver.OracleDriver");("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.2. Define the Connection URLDefine the Connection URL String String hosthost = "dbhost.yourcompany.com"; = "dbhost.yourcompany.com"; String dbName = "someName";String dbName = "someName"; int port = 1234;int port = 1234; String oracleURL = "String oracleURL = "jdbc:oracle:thin:@jdbc:oracle:thin:@" + " + hosthost + + ":" + port + ":" + ":" + port + ":" + dbNamedbName;; String sybaseURL = "String sybaseURL = "jdbc:sybase:Tds:jdbc:sybase:Tds:" + " + hosthost + + ":" + port + ":" + "?SERVICENAME=" + ":" + port + ":" + "?SERVICENAME=" + dbNamedbName;;

Page 10: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

JDBC: Details of JDBC: Details of Process, cont.Process, cont.

3.3. Establish the ConnectionEstablish the Connection

String username = "jay_debesee";String username = "jay_debesee";

String password = "secret";String password = "secret";

Connection connection =Connection connection =

DriverManager.getConnectionDriverManager.getConnection(oracleURL,(oracleURL,

username,username, password); password);

4.4. Create a StatementCreate a Statement

Statement statement =Statement statement = connection.createStatement();connection.createStatement();

Page 11: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

JDBC: Details of JDBC: Details of Process, cont.Process, cont.

5.5. Execute a QueryExecute a Query

String query = "SELECT col1, col2, col3 FROM sometable";String query = "SELECT col1, col2, col3 FROM sometable";

ResultSet resultSet = ResultSet resultSet = statement.executeQuerystatement.executeQuery(query);(query);

– To To modifymodify the database, use the database, use executeUpdateexecuteUpdate, supplying a string , supplying a string that uses that uses UPDATEUPDATE, , INSERTINSERT, or , or DELETEDELETE

– Use Use setQueryTimeoutsetQueryTimeout to specify a to specify a maximum delay to wait for resultsmaximum delay to wait for results

Page 12: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

JDBC: Details of JDBC: Details of Process, cont.Process, cont.6.6. Process the ResultProcess the Result

while(resultSet.next()) {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 0First column has index 1, not 0– ResultSetResultSet provides various provides various getgetXxxXxx methods that methods that

take a column index or name and returns the datatake a column index or name and returns the data

7.7. Close the ConnectionClose the Connection connection.close();connection.close();

– As opening a connection is expensive, postpone this As opening a connection is expensive, postpone this step if additional database operations are expectedstep if additional database operations are expected

Page 13: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

import java.sql.*;import java.sql.*;

public class TestDB {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.DriverManager.getConnectiongetConnection(url, user, password);(url, user, password); Statement statement = connection.Statement statement = connection.createStatementcreateStatement();(); 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.ResultSet results = statement.executeQueryexecuteQuery(query);(query);

Basic Basic JDBC JDBC ExampleExample

Page 14: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

// 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.printlnSystem.out.println (pad((pad(results.getStringresults.getString(1), 4) + " | " +(1), 4) + " | " + pad(pad(results.getStringresults.getString(2), 4) + " | " +(2), 4) + " | " + results.getStringresults.getString(3) + "\n" + divider);(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.Basic JDBC Example, cont.

Page 15: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

Microsoft Access Microsoft Access ExampleExample Northwind sample databaseNorthwind sample database

• Northwind.mdb located in C:\Program Files\Microsoft Office\Office\Samples

Page 16: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

MS Access Example: MS Access Example: Create a data sourceCreate a data source

Create System (Data Source Name) Create System (Data Source Name) DSN through ODBC data sourceDSN through ODBC data source

Page 17: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

MS Access Example: MS Access Example: Java CodeJava Codeimport java.io.*;import java.io.*;import java.sql.*;import java.sql.*;import javax.servlet.*;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.http.*;

public class NorthwindServlet extends HttpServlet {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(out.println(doQuery()doQuery());); } ...} ...}}

Page 18: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

public static String doQuery() {public static String doQuery() { StringBuffer buffer = new StringBuffer();StringBuffer buffer = new StringBuffer(); try { try { Class.forName(Class.forName("sun.jdbc.odbc.JdbcOdbcDriver""sun.jdbc.odbc.JdbcOdbcDriver");); Connection connection = Connection connection = DriverManager.getConnection(DriverManager.getConnection("jdbc:odbc:Northwind","","""jdbc:odbc:Northwind","","");); Statement statement = connection.createStatement();Statement statement = connection.createStatement(); String query = "String query = "SELECT FirstName, LastName FROM EmployeesSELECT 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 MS Access Example Example (Continue(Continued)d)

Page 19: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

MS Access Example, MS Access Example, ResultResult

Page 20: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

MySQL & Connector/JMySQL & Connector/J

Page 21: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

ResultSet ResultSet

OverviewOverview– A A ResultSetResultSet contains the results of the SQL contains the results of the SQL

queryquery Represented by a table with rows and columnsRepresented by a table with rows and columns In JDBC 1.0 you can In JDBC 1.0 you can only proceed forwardonly proceed forward through through

the rows using the rows using nextnext

Useful MethodsUseful Methods All methods can throw a All methods can throw a SQLExceptionSQLException

– closeclose Releases the JDBC and database resourcesReleases the JDBC and database resources The result set is The result set is automatically closedautomatically closed when the when the

associated associated StatementStatement object object executes a new queryexecutes a new query

Page 22: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

ResultSet (Continued) ResultSet (Continued)

Useful MethodsUseful Methods– getMetaDataObjectgetMetaDataObject

Returns a Returns a ResultSetMetaDataResultSetMetaData object containing object containing information about the columns in the information about the columns in the ResultSetResultSet

– nextnext Attempts to move to the Attempts to move to the next rownext row in the in the ResultSetResultSet

– If successful If successful truetrue is returned; otherwise, is returned; otherwise, falsefalse– The first call to next positions the cursor a the first rowThe first call to next positions the cursor a the first row– Calling next clears the Calling next clears the SQLWarningSQLWarning chain chain

– getWarningsgetWarnings Returns the first Returns the first SQLWarningSQLWarning or or nullnull if no warnings if no warnings

occurredoccurred

Page 23: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

ResultSet (Continued) ResultSet (Continued)

Useful MethodsUseful Methods– findColumnfindColumn

Returns the corresponding integer value corresponding to the Returns the corresponding integer value corresponding to the specified column namespecified column name

Column numbers in the result set do not necessarily map to the Column numbers in the result set do not necessarily map to the same column numbers in the databasesame column numbers in the database

– getgetXxxXxx Returns the value from the column specified by Returns the value from the column specified by column namecolumn name or or

column indexcolumn index as an as an XxxXxx Java type Java type

Returns 0 or Returns 0 or nullnull, if the value is a SQL NULL, if the value is a SQL NULL

Legal Legal getgetXxxXxx types: types:

– wasNullwasNull Used to check if the last Used to check if the last getgetXxxXxx read was a SQL read was a SQL NULLNULL

double byte int Date Stringfloat short long Time Object

Page 24: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

Using StatementUsing Statement

OverviewOverview– Through the Statement object, SQL Through the Statement object, SQL

statements are sent to the database. statements are sent to the database. – Two types of statement objects are Two types of statement objects are

available:available: Statement Statement

– for executing a for executing a simple SQLsimple SQL statements statements PreparedStatement PreparedStatement

– for executing a for executing a precompiled SQL statementprecompiled SQL statement passing in parameterspassing in parameters

Page 25: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

Useful Statement Useful Statement MethodsMethods executeQueryexecuteQuery

– Executes the SQL query and returns the data in a table Executes the SQL query and returns the data in a table (ResultSet)(ResultSet)

– The resulting table may be empty but never nullThe resulting table may be empty but never null

ResultSet results = statement.executeQuery("SELECT a, b FROM table");ResultSet results = statement.executeQuery("SELECT a, b FROM table");

executeUpdateexecuteUpdate– Used to execute for INSERT, UPDATE, or DELETE SQL statements Used to execute for INSERT, UPDATE, or DELETE SQL statements – The return is the number of rows that were affected in the The return is the number of rows that were affected in the

databasedatabase– Supports Data Definition Language (DDL) statements CREATE Supports Data Definition Language (DDL) statements CREATE

TABLE, DROP TABLE and ALTER TABLETABLE, DROP TABLE and ALTER TABLE

int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" +int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" +

"WHERE STATUS=0");"WHERE STATUS=0");

Page 26: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

Useful Statement Useful Statement Methods (Continued)Methods (Continued) executeexecute

– Generic method for executing stored procedures and Generic method for executing stored procedures and prepared statementsprepared statements

– Rarely used (for multiple return result sets)Rarely used (for multiple return result sets)– The statement execution may or may not return a The statement execution may or may not return a

ResultSet (use statement.getResultSet). If the return ResultSet (use statement.getResultSet). If the return value is true, two or more result sets were produced value is true, two or more result sets were produced

getMaxRows/setMaxRowsgetMaxRows/setMaxRows– Determines the number of rows a Determines the number of rows a ResultSetResultSet may may

containcontain– Unless explicitly set, the number of rows are unlimitedUnless explicitly set, the number of rows are unlimited

getQueryTimeout/setQueryTimeoutgetQueryTimeout/setQueryTimeout– Specifies the amount of a time a driver will wait for a Specifies the amount of a time a driver will wait for a

STATEMENT to complete before throwing a STATEMENT to complete before throwing a SQLExceptionSQLException

Page 27: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

Prepared Statements Prepared Statements (Precompiled Queries)(Precompiled Queries) IdeaIdea

– If you are going to execute If you are going to execute similar SQL statementssimilar SQL statements multiple times, using multiple times, using “prepared” (parameterized)“prepared” (parameterized) statementsstatements can be more efficient can be more efficient

– Create a statement in standard form that is sent to the Create a statement in standard form that is sent to the database for compilation before actually being used database for compilation before actually being used

– Each time you use it, you simply replace some of the Each time you use it, you simply replace some of the marked parameters using the marked parameters using the setXxxsetXxx methods methods

As PreparedStatement inherits from Statement As PreparedStatement inherits from Statement the corresponding execute methods have no the corresponding execute methods have no parametersparameters– execute()execute()– executeQuery()executeQuery()– executeUpdate()executeUpdate()

Page 28: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

Prepared Statement, Prepared Statement, ExampleExample

Connection connection =Connection connection = DriverManager.getConnection(url, user, password);DriverManager.getConnection(url, user, password);PreparedStatement statement =PreparedStatement statement = connection.prepareStatement("UPDATE employees " +connection.prepareStatement("UPDATE employees " + "SET salary = ? " +"SET salary = ? " + "WHERE id = ?");"WHERE id = ?");int[] newSalaries = getSalaries();int[] newSalaries = getSalaries();int[] employeeIDs = getIDs();int[] employeeIDs = getIDs();for(int i=0; i<employeeIDs.length; i++) {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();}}

Page 29: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

Useful Prepared Useful Prepared Statement MethodsStatement Methods setsetXxxXxx

– Sets the indicated parameter (?) in the SQL statement Sets the indicated parameter (?) in the SQL statement to the valueto the value

clearParametersclearParameters– Clears all set parameter values in the statementClears all set parameter values in the statement

Handling Servlet DataHandling Servlet Data– Query data obtained from a user through an HTML Query data obtained from a user through an HTML

form form may have SQL or special charactersmay have SQL or special characters that may that may require escape sequencesrequire escape sequences

– To handle the To handle the special charactersspecial characters, pass the string to , pass the string to the the PreparedStatementPreparedStatement setStringsetString method which will method which will automatically escape the string as necessaryautomatically escape the string as necessary

Page 30: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

Exception HandlingException Handling

SQL ExceptionsSQL Exceptions– Nearly every JDBC method can throw a Nearly every JDBC method can throw a SQLExceptionSQLException in response to a data access in response to a data access error error

– If more than one error occurs, they are If more than one error occurs, they are chained togetherchained together

– SQL exceptions contain:SQL exceptions contain: Description of the error, Description of the error, getMessagegetMessage The SQLState (Open Group SQL specification) The SQLState (Open Group SQL specification)

identifying the exception, identifying the exception, getSQLStategetSQLState A vendor-specific integer, error code, A vendor-specific integer, error code, getErrorCodegetErrorCode A chain to the next A chain to the next SQLExceptionSQLException, , getNextExceptiongetNextException

Page 31: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

SQL Exception SQL Exception ExampleExampletry {try {

... // JDBC statement. ... // JDBC statement.

} catch (} catch (SQLException sqleSQLException 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 = sqle.getNextException()sqle.getNextException();; }}}}

– Don’t make assumptions about the state of a transaction after Don’t make assumptions about the state of a transaction after an exception occursan exception occurs

– The safest best is to attempt a rollback to return to the initial The safest best is to attempt a rollback to return to the initial state state

Page 32: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

SQL WarningsSQL Warnings

SQLWarnings are rare, but provide information about the SQLWarnings are rare, but provide information about the database access warnings 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:

– ConnectionConnection– StatementStatement– ResultSetResultSet

Call Call getWarninggetWarning to obtain the warning object, and to obtain the warning object, and getNextWarninggetNextWarning (on the warning object) for any (on the warning object) for any additional warningsadditional warnings

Warnings are Warnings are clearedcleared on the object each time the on the object each time the statement is executedstatement is executed

Page 33: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

SQL Warning, ExampleSQL Warning, ExampleResultSet results = statement.executeQuery(someQuery);ResultSet results = statement.executeQuery(someQuery);SQLWarning warning = statement.getWarnings();SQLWarning warning = statement.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();}}while (results.next()) {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(); }} }}

Page 34: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

SummarySummary

In JDBC 1.0, can only step forward (In JDBC 1.0, can only step forward (nextnext) ) through the through the ResultSetResultSet

Be sure to handle the situation where Be sure to handle the situation where getXxxgetXxx returns a NULL returns a NULL

Understand the relationship between:Understand the relationship between:– Connection objectConnection object– Statement objectStatement object– ResultSet objectResultSet object

Be default, a connection is auto-commitBe default, a connection is auto-commit SQL Exceptions and Warnings are chained SQL Exceptions and Warnings are chained

togethertogether

Page 35: Java: JDBC INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

ReferencesReferences

CWP2: Chapter 22CWP2: Chapter 22 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://industry.java.sun.com/products/jdbc/drivershttp://industry.java.sun.com/products/jdbc/drivers http://www.mysql.com/http://www.mysql.com/

The End.The End. Thank you for patience!Thank you for patience!