JDBC
JDBC
Web
programming
Introduction to JDBC
Agenda
Overview of JDBC technology JDBC drivers Seven basic steps in using JDBC Retrieving data from a ResultSet Using prepared and callable statements Handling SQL exceptions Submitting multiple statements as a transaction
JDBC
www.corewebprogramming.com
JDBC Introduction
JDBC provides a standard library for accessing relational databases
API standardizes
Way to establish connection to database Approach to initiating queries Method to create stored (parameterized) queries The data structure of query result (table) Determining the number of columns Looking up metadata, etc.
Note: JDBC is not officially an acronym; unofficially, Java Database Connectivity is commonly used www.corewebprogramming.com JDBC
On-line Resources
Suns JDBC Site
http://java.sun.com/products/jdbc/
JDBC Tutorial
http://java.sun.com/docs/books/tutorial/jdbc/
JDBC
www.corewebprogramming.com
JDBC Drivers
http://technet.oracle.com/software/tech/java/sqlj_jdbc/ content.html Requires free registration
Certification
http://www.oracle.com/education/certification/
5 JDBC
www.corewebprogramming.com
JDBC Drivers
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
6 JDBC
Java Application
JDBC API
Database
Database
www.corewebprogramming.com
Java Type
boolean byte short int long float double byte[]
JDBC Type
NUMERIC DECIMAL DATE TIME TIMESTAMP CLOB BLOB ARRAY DISTINCT STRUCT REF JAVA_OBJECT
Java Type
BigDecimal java.sql.Date java.sql.Timestamp Clob* Blob* Array* mapping of underlying type Struct* Ref* underlying Java class
String
JDBC
www.corewebprogramming.com
JDBC
www.corewebprogramming.com
www.corewebprogramming.com
10
JDBC
www.corewebprogramming.com
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
11
JDBC
www.corewebprogramming.com
First column has index 1, not 0 ResultSet provides various getXxx methods that take a column index or name and returns the data
As opening a connection is expensive, postpone this step if additional database operations are expected
12 JDBC
www.corewebprogramming.com
13
JDBC
www.corewebprogramming.com
www.corewebprogramming.com
16
JDBC
www.corewebprogramming.com
public class NorthwindServlet extends HttpServlet { public static void main(String[] args) { System.out.println(doQuery()); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(doQuery()); } ... }
17 JDBC
www.corewebprogramming.com
18
19
JDBC
www.corewebprogramming.com
ResultSet
Overview
A ResultSet contains the results of the SQL query
Represented by a table with rows and columns In JDBC 1.0 you can only proceed forward through the rows using next
Useful Methods
All methods can throw a SQLException
close
Releases the JDBC and database resources The result set is automatically closed when the associated Statement object executes a new query
getMetaDataObject
Returns a ResultSetMetaData object containing information about the columns in the ResultSet
20 JDBC
www.corewebprogramming.com
ResultSet (Continued)
Useful Methods
next 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
21
JDBC
www.corewebprogramming.com
ResultSet (Continued)
Useful Methods
findColumn
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
getXxx
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 Legal getXxx types:
wasNull
22 JDBC
double float
byte short
String Object
www.corewebprogramming.com
Using MetaData
Idea
From a ResultSet (the return type of executeQuery), derive a ResultSetMetaData object Use that object to look up the number, names, and types of columns
23 JDBC
getColumnDisplaySize
Returns the maximum width of the specified column in characters
getColumnName/getColumnLabel
The getColumnName method returns the database name of the column The getColumnLabel method returns the suggested column label for printouts
getColumnType
Returns the SQL type for the column to compare against types in java.sql.Types
24 JDBC
www.corewebprogramming.com
isSearchable
Returns true or false if the column can be used in a WHERE clause
isReadOnly/isWritable
The isReadOnly method indicates if the column is definitely not writable The isWritable method indicates whether it is possible for a write to succeed
25 JDBC
www.corewebprogramming.com
www.corewebprogramming.com
www.corewebprogramming.com
28
JDBC
www.corewebprogramming.com
Using Statement
Overview
Through the Statement object, SQL statements are sent to the database. Three types of statement objects are available:
Statement for executing a simple SQL statements PreparedStatement for executing a precompiled SQL statement passing in parameters CallableStatement for executing a database stored procedure
29
JDBC
www.corewebprogramming.com
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");
30
JDBC
www.corewebprogramming.com
getMaxRows/setMaxRows
Determines the number of rows a ResultSet may contain Unless explicitly set, the number of rows are unlimited (return value of 0) Specifies the amount of a time a driver will wait for a STATEMENT to complete before throwing a SQLException www.corewebprogramming.com
getQueryTimeout/setQueryTimeout
31 JDBC
As PreparedStatement inherits from Statement the corresponding execute methods have no parameters
execute() executeQuery() executeUpdate()
32
JDBC
www.corewebprogramming.com
33
JDBC
www.corewebprogramming.com
clearParameters
Clears all set parameter values in the statement
www.corewebprogramming.com
Callable Statements
Idea
Permit calls to a stored procedures in a database
Advantage
Syntax errors are caught a compile time and not a runtime Stored procedures execute much faster than dynamic SQL The programmer need to know only about the input and output parameters for the stored procedure, not the table structure or internal details of the stored procedure
35
JDBC
www.corewebprogramming.com
36
JDBC
www.corewebprogramming.com
37
JDBC
www.corewebprogramming.com
www.corewebprogramming.com
registerOutputParameter
Binds indexed output parameter to a JDBC type Can also provide a scale parameter to specify the number of digits to the right of the decimal point for NUMERIC or DECIMAL JDBC types
statement.registerOutParameter(2, Types.DECIMAL, 3);
39 JDBC
www.corewebprogramming.com
Exception Handling
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 The SQLState (Open Group SQL specification) identifying the exception, getSQLState A vendor-specific integer, error code, getErrorCode A chain to the next SQLException, getNextException
40
JDBC
www.corewebprogramming.com
Dont 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
41 JDBC
www.corewebprogramming.com
Transactions
Idea
By default, after each SQL statement is executed the changes are automatically committed to the database Turn auto-commit off to group two or more statements together into a transaction
connection.setAutoCommit(false)
Call commit to permanently record the changes to the database after executing a group of statements Call rollback if an error occurs
42
JDBC
www.corewebprogramming.com
Transactions: Example
Connection connection = DriverManager.getConnection(url, username, passwd); connection.setAutoCommit(false); try { statement.executeUpdate(...); statement.executeUpdate(...); ... } catch (SQLException e) { try { connection.rollback(); } catch (SQLException sqle) { // report problem } } finally { try { connection.commit(); connection.close(); } catch (SQLException sqle) { } }
43 JDBC
www.corewebprogramming.com
commit
Force all changes since the last call to commit to become permanent Any database locks currently held by this Connection object are released
rollback
Drops all changes since the previous call to commit Releases any database locks held by this Connection object
44 JDBC
www.corewebprogramming.com
Performing JDBC queries and formatting output are common tasks, so create helper classes to perform this function: DatabaseUtilities and DBResults
printTable
Given a table name, this method connects to the database, retrieves all the rows, and prints them on the standard output
printTableData
Given a DBResults object from a previous query, prints the results to standard output. Useful for debugging
45 JDBC
www.corewebprogramming.com
46
JDBC
www.corewebprogramming.com
Summary
In JDBC 1.0, can only step forward (next) through the ResultSet MetaDataResultSet provides details about returned ResultSet Improve performance through prepared statements Be sure to handle the situation where getXxx returns a NULL Be default, a connection is auto-commit SQL Exceptions are chained together
47
JDBC
www.corewebprogramming.com
core
Web
programming
Questions?
48