Se15 JDBC
Se15 JDBC
Se15 JDBC
with JDBC
Core Servlets & JSP book: www.coreservlets.com
More Servlets & JSP book: www.moreservlets.com
Servlet and JSP Training Courses: courses.coreservlets.com
Slides © Marty Hall, http://www.moreservlets.com, book © Sun Microsystems Press
Overview
• 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
3 JDBC www.moreservlets.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.
– API does not standardize SQL syntax
• JDBC is not embedded SQL
– JDBC classes are in the java.sql package
• Note: JDBC is not officially an acronym;
unofficially, “Java DataBase Connectivity” is
commonly used www.moreservlets.com
4 JDBC
On-line Resources
• Sun’s JDBC Site
– http://java.sun.com/products/jdbc/
• JDBC Tutorial
– http://java.sun.com/docs/books/tutorial/jdbc/
• List of Available JDBC Drivers
– http://industry.java.sun.com/products/jdbc/drivers/
• API for java.sql
– http://java.sun.com/j2se/1.4/docs/api/java/sql/
package-summary.html
5 JDBC www.moreservlets.com
Oracle On-line Resources
• JDBC Road Map
– http://technet.oracle.com/tech/java/jroadmap/index2.htm?
Info&jdbc/listing.htm
• SQLJ & JDBC Basic Samples
– http://technet.oracle.com/tech/java/sqlj_jdbc/index2.htm?
Code&files/basic/basic.htm
• JDBC Drivers
– http://technet.oracle.com/software/tech/java/sqlj_jdbc/
htdocs/listing.htm
– Requires free registration
• Certification
– http://technet.oracle.com/training/certification/
6 JDBC www.moreservlets.com
JDBC Drivers
• JDBC consists of two parts:
– JDBC API, a purely Java Application
Java-based API
JDBC API
– JDBC Driver Manager,which
communicates with JDBC Driver Manager
vendor-specific drivers that JDBC Driver API
perform the real communication
with the database. JDBC-ODBC
Bridge
Vendor Specific
JDBC Driver
– No changes needed
to server
– Driver (translator) needed Database
on client
7 JDBC www.moreservlets.com
JDBC Data Types
8 JDBC www.moreservlets.com
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 JDBC www.moreservlets.com
JDBC: Details of Process
1. Load the driver
try {
Class.forName("connect.microsoft.MicrosoftDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch { ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " cnfe);
}
2. Define the Connection URL
String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host +
":" + port + ":" + dbName;
String sybaseURL = "jdbc:sybase:Tds:" + host +
":" + port + ":" +
"?SERVICENAME=" + dbName;
10 JDBC www.moreservlets.com
JDBC: Details of Process
(Continued)
3. Establish the Connection
String username = "jay_debesee";
String password = "secret";
Connection connection =
DriverManager.getConnection(oracleURL,
username,
password);
5. Execute a Query
String query =
"SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet =
statement.executeQuery(query);
14 JDBC www.moreservlets.com
Using Microsoft Access via
ODBC
• Click Start, Settings, Control Panel,
Administrative Tools, Data Sources, System
DSN, and select Add
15 JDBC www.moreservlets.com
Using Microsoft Access via
ODBC (Continued)
• Select Microsoft Access Driver, Finish, type a
name under Data Source Name, and hit Select
16 JDBC www.moreservlets.com
Using Microsoft Access via
ODBC (Continued)
• Navigate to the Samples directory of MS Office,
select Northwind.mdb, hit OK, then hit OK in
following two windows
17 JDBC www.moreservlets.com
Using Microsoft Access via
ODBC (Continued)
• Use sun.jdbc.odbc.JdbcOdbcDriver as the
class name of the JDBC driver.
– Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Use "jdbc:odbc:Northwind" as the database
address, and use empty strings for the
username and password.
– Connection connection =
DriverManager.getConnection("jdbc:odbc:Northwind",
"","");
18 JDBC www.moreservlets.com
Simple Standalone Northwind
Test
package coreservlets;
import java.sql.*;
20 JDBC www.moreservlets.com
Simple Standalone Northwind
Test (Continued)
// Print results.
while(resultSet.next()) {
// First name
System.out.print(resultSet.getString(1) + " ");
// Last name
System.out.println(resultSet.getString(2));
}
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
}
}
}
21 JDBC www.moreservlets.com
Simple Standalone Northwind
Test: Results
Prompt> java coreservlets.NorthwindTest
Employees
=========
Nancy Davolio
Andrew Fuller
Janet Leverling
Margaret Peacock
Steven Buchanan
Michael Suyama
Robert King
Laura Callahan
Anne Dodsworth
22 JDBC www.moreservlets.com
Using MetaData
• System-wide data
– connection.getMetaData().getDatabaseProductName()
– connection.getMetaData().getDatabaseProductVersion()
• Table-specific data
– resultSet.getMetaData().getColumnCount()
• When using the result, remember that
the index starts at 1, not 0
– resultSet.getMetaData().getColumnName()
23 JDBC www.moreservlets.com
Using MetaData: Example
public class NorthwindServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
… out.println(docType + …);
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:Northwind";
String username = "";
String password = "";
String tableName = request.getParameter("tableName");
if ((tableName == null) || (tableName.equals(""))) {
tableName = "employees";
}
showTable(driver, url, username, password,
tableName, out);
out.println("</CENTER></BODY></HTML>");
}
24 JDBC www.moreservlets.com
Using MetaData: Example
(Continued)
private void showTable(String driver,
String url,
String username,
String password,
String tableName,
PrintWriter out) {
try {
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username, password);
DatabaseMetaData dbMetaData = connection.getMetaData();
out.println("<UL>");
String productName =
dbMetaData.getDatabaseProductName();
out.println(" <LI><B>Database:</B> " +
productName);
String productVersion =
dbMetaData.getDatabaseProductVersion();
out.println(" <LI><B>Version:</B> " +
productVersion +
"\n</UL>");
25 JDBC www.moreservlets.com
Using MetaData: Example
(Continued)
Statement statement = connection.createStatement();
String query =
"SELECT * FROM " + tableName;
ResultSet resultSet = statement.executeQuery(query);
out.println("<TABLE BORDER=1>");
ResultSetMetaData resultsMetaData =
resultSet.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
out.println("<TR>");
for(int i=1; i<columnCount+1; i++) {
out.print("<TH>" + resultsMetaData.getColumnName(i));
}
out.println();
while(resultSet.next()) {
out.println("<TR>");
for(int i=1; i<columnCount+1; i++) {
out.print("<TD>" + resultSet.getString(i));
}
out.println();
}
out.println("</TABLE>");
26 JDBC www.moreservlets.com
Using MetaData: Results
27 JDBC www.moreservlets.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 statement
• PreparedStatement
– For executing a precompiled SQL statement passing in parameters
• CallableStatement
– For executing a database stored procedure
28 JDBC www.moreservlets.com
Useful Statement Methods
• 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
– 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");
29 JDBC www.moreservlets.com
Useful Statement Methods
(Continued)
• 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
– Determines the maximum number of rows a
ResultSet may contain
– Unless explicitly set, the number of rows is unlimited
(return value of 0)
• getQueryTimeout/setQueryTimeout
– Specifies the amount of a time a driver will wait for a
STATEMENT to complete before throwing a
30
SQLException
JDBC www.moreservlets.com
Prepared Statements
(Precompiled Queries)
• 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
– execute()
– executeQuery()
– executeUpdate()
31 JDBC www.moreservlets.com
Prepared Statement, Example
Connection connection =
DriverManager.getConnection(url, user,
password);
PreparedStatement statement =
connection.prepareStatement("UPDATE employees "+
"SET salary = ? " +
"WHERE id = ?");
int[] newSalaries = getSalaries();
int[] employeeIDs = getIDs();
for(int i=0; i<employeeIDs.length; i++) {
statement.setInt(1, newSalaries[i]);
statement.setInt(2, employeeIDs[i]);
statement.executeUpdate();
}
32 JDBC www.moreservlets.com
Useful Prepared Statement
Methods
• setXxx
– Sets the indicated parameter (?) in the SQL statement to
the value
• clearParameters
– Clears all set parameter values in the statement
34 JDBC www.moreservlets.com
Transactions: Example
Connection connection =
DriverManager.getConnection(url, username, passwd);
connection.setAutoCommit(false);
try {
statement.executeUpdate(...);
statement.executeUpdate(...);
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException sqle) {
// report problem
}
} finally {
try {
connection.close();
} catch (SQLException sqle) { }
}
35 JDBC www.moreservlets.com
Useful Connection Methods
(for Transactions)
• getAutoCommit/setAutoCommit
– By default, a connection is set to auto-commit
– Retrieves or sets the auto-commit mode
• 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
36 JDBC www.moreservlets.com
More JDBC Options
• Stored procedures
• Changing buffer size
• Connection pooling
• JSP Standard Tag Library (JSTL) –
custom tags to hide JDBC details
37 JDBC www.moreservlets.com
Summary
• You use the same Java syntax with all
databases
– Translation to native format is done on the client via a
JDBC driver
– Standardized Java syntax does not equate to
standardized SQL syntax
• 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
38
7.
JDBC
Close the connection www.moreservlets.com
Questions?