SlideShare a Scribd company logo
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Introduction
to JDBC
JDBC2 www.corewebprogramming.com
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
JDBC3 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.
– API does not standardize SQL syntax
• JDBC is not embedded SQL
– JDBC class located in java.sql package
• Note: JDBC is not officially an acronym; unofficially,
“Java Database Connectivity” is commonly used
JDBC4 www.corewebprogramming.com
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
JDBC5 www.corewebprogramming.com
Oracle On-line Resources
• Java Center
– http://technet.oracle.com/tech/java/content.html
• SQLJ & JDBC Basic Samples
– http://technet.oracle.com/sample_code/tech/java/
sqlj_jdbc/content.html
• JDBC Drivers
– http://technet.oracle.com/software/tech/java/sqlj_jdbc/
content.html
– Requires free registration
• Certification
– http://www.oracle.com/education/certification/
JDBC6 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
Database
JDBC Driver Manager
Java Application
JDBC API
JDBC Driver API
Vendor Specific
JDBC Driver
Vendor Specific
ODBC Driver
JDBC-ODBC
Bridge
Database
JDBC7 www.corewebprogramming.com
JDBC Data Types
JDBC Type Java Type
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE
BINARY byte[]
VARBINARY
LONGVARBINARY
CHAR String
VARCHAR
LONGVARCHAR
JDBC Type Java Type
NUMERIC BigDecimal
DECIMAL
DATE java.sql.Date
TIME java.sql.Timestamp
TIMESTAMP
CLOB Clob*
BLOB Blob*
ARRAY Array*
DISTINCT mapping of underlying type
STRUCT Struct*
REF Ref*
JAVA_OBJECT underlying Java class
*SQL3 data type supported in JDBC 2.0
JDBC8 www.corewebprogramming.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
JDBC9 www.corewebprogramming.com
JDBC: Details of Process
1. Load the driver
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("org.gjt.mm.mysql.Driver");
} 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 mysqlURL = "jdbc:mysql://" + host +
":" + port + "/" + dbName;
JDBC10 www.corewebprogramming.com
JDBC: Details of Process, cont.
3. Establish the Connection
String username = "jay_debesee";
String password = "secret";
Connection connection =
DriverManager.getConnection(oracleURL,
username,
password);
• Optionally, look up information about the database
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion =
dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion);
JDBC11 www.corewebprogramming.com
JDBC: Details of Process, cont.
4. Create a Statement
Statement statement = connection.createStatement();
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
JDBC12 www.corewebprogramming.com
JDBC: Details of Process, cont.
6. Process the Result
while(resultSet.next()) {
System.out.println(resultSet.getString(1) + " " +
resultSet.getString(2) + " " +
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();
– As opening a connection is expensive, postpone this
step if additional database operations are expected
JDBC13 www.corewebprogramming.com
Basic JDBC Example
import java.sql.*;
public class TestDB {
public static void main(String[] args) {
// Use driver from Connect SW.
String driver = "connect.microsoft.MicrosoftDriver";
try {
Class.forName(driver);
String url = "jdbc:ff-microsoft://" + // FastForward
"dbtest.apl.jhu.edu:1433/" + // Host:port
"pubs"; // Database name
String user = "sa", password="";
Connection connection =
DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String query =
"SELECT col1, col2, col3 FROM testDB";
// Execute query and save results.
ResultSet results = statement.executeQuery(query);
JDBC14 www.corewebprogramming.com
Basic JDBC Example, cont.
// Print column names.
String divider = "-----+------+-----";
System.out.println("Col1 | Col2 | Col3n" + divider);
// Print results
while(results.next()) {
System.out.println
(pad(results.getString(1), 4) + " | " +
pad(results.getString(2), 4) + " | " +
results.getString(3) + "n" + divider);
}
connection.close();
} catch(ClassNotFoundException cnfe) {
System.out.println("No such class: " + driver);
} catch(SQLException se) {
System.out.println("SQLException: " + se);
}
}
...
JDBC15 www.corewebprogramming.com
Microsoft Access Example
• Northwind sample database
• Northwind.mdb located in C:Program FilesMicrosoft OfficeOfficeSamples
• http://office.microsoft.com/downloads/2000/Nwind2k.aspx
JDBC16 www.corewebprogramming.com
MS Access Example: Setup
• Create System DSN through ODBC data
source
JDBC17 www.corewebprogramming.com
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) {
System.out.println(doQuery());
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(doQuery());
}
...
}
JDBC18 www.corewebprogramming.com
MS Access Example
(Continued)
public static String doQuery() {
StringBuffer buffer = new StringBuffer();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connection =
DriverManager.getConnection("jdbc:odbc:Northwind","","");
Statement statement = connection.createStatement();
String query = "SELECT FirstName, LastName FROM Employees";
ResultSet result = statement.executeQuery(query);
buffer.append("Northwind Databasenn");
while (result.next()) {
buffer.append(result.getString(1) + " " +
result.getString(2) + "n");
}
connection.close();
} catch (ClassNotFoundException cnfe) {
buffer.append("Couldn't find class file" + cnfe);
} catch (SQLException sqle) {
buffer.append("SQL Exception: " + sqle);
}
return buffer.toString();
}
JDBC19 www.corewebprogramming.com
MS Access Example, Result
JDBC20 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
JDBC21 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
JDBC22 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
• Used to check if the last getXxx read was a SQL
NULL
double byte int Date String
float short long Time Object
JDBC23 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
• ResultSetMetaData answers the following
questions:
– How many columns are in the result set?
– What is the name of a given column?
– Are the column names case sensitive?
– What is the data type of a specific column?
– What is the maximum character size of a column?
– Can you search on a given column?
JDBC24 www.corewebprogramming.com
Useful MetaData Methods
• getColumnCount
– Returns the number of columns in the result set
• 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
JDBC25 www.corewebprogramming.com
Useful MetaData Methods
(Continued)
• isNullable
– Indicates whether storing a NULL in the column is legal
– Compare the return value against ResultSet constants:
columnNoNulls, columnNullable,
columnNullableUnknown
• 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
JDBC26 www.corewebprogramming.com
Using MetaData: Example
Connection connection =
DriverManager.getConnection(url, username, password);
// Look up info about the database as a whole.
DatabaseMetaData dbMetaData =
connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion =
dbMetaData.getDatabaseProductVersion();
...
Statement statement = connection.createStatement();
String query = "SELECT * FROM fruits";
ResultSet resultSet = statement.executeQuery(query);
JDBC27 www.corewebprogramming.com
Using MetaData: Example
// Look up information about a particular table.
ResultSetMetaData resultsMetaData =
resultSet.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
// Column index starts at 1 (a la SQL) not 0 (a la Java).
for(int i=1; i<columnCount+1; i++) {
System.out.print(resultsMetaData.getColumnName(i) +
" ");
}
System.out.println();
// Print results.
while(resultSet.next()) {
// Quarter
System.out.print(" " + resultSet.getInt(1));
// Number of Apples
...
}
JDBC28 www.corewebprogramming.com
Using MetaData, Result
Prompt> java cwp.FruitTest dbhost1.apl.jhu.edu PTE
hall xxxx oracle
Database: Oracle
Version: Oracle7 Server Release 7.2.3.0.0 – Production Release
PL/SQL Release 2.2.3.0.0 - Production
Comparing Apples and Oranges
============================
QUARTER APPLES APPLESALES ORANGES ORANGESALES TOPSELLER
1 32248 $3547.28 18459 $3138.03 Maria
2 35009 $3850.99 18722 $3182.74 Bob
3 39393 $4333.23 18999 $3229.83 Joe
4 42001 $4620.11 19333 $3286.61 Maria
JDBC29 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
JDBC30 www.corewebprogramming.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");
JDBC31 www.corewebprogramming.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 number of rows a ResultSet may
contain
– Unless explicitly set, the number of rows are 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
SQLException
JDBC32 www.corewebprogramming.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()
JDBC33 www.corewebprogramming.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();
}
JDBC34 www.corewebprogramming.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
• 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
JDBC35 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
JDBC36 www.corewebprogramming.com
Callable Statements, cont.
• Stored Procedure Syntax
– Procedure with no parameters
{ call procedure_name }
– Procedure with input parameters
{ call procedure_name(?, ?, ...) }
– Procedure with output parameters
{ ? = call procedure_name(?, ?, ...) }
CallableStatement statement =
connection.prepareCall("{ call procedure(?, ?) }");
JDBC37 www.corewebprogramming.com
Callable Statements, cont.
• Output Parameters
– Register the JDBC type of each output parameter through
registerOutParameter before calling execute
statement.registerOutParameter(n, Types.FLOAT);
– Use getXxx to access stored procedure return values
JDBC38 www.corewebprogramming.com
Callable Statements: Example
String procedure = "{ ? = call isValidUser(?, ?) }";
CallableStatement statement =
connection.prepareCall(procedure);
statement.setString(2, username);
statement.setString(3, password);
statement.registerOutParameter(1, Types.BIT);
statement.execute();
if (statement.getBoolean(1)) {
// Valid Username, password.
...
} else {
// Invalid username, password.
...
}
JDBC39 www.corewebprogramming.com
Useful CallableStatement
Methods
• CallableStatement inherits from
PreparedStatement
• getXxx(int parameterIndex)
– Retrieves the JDBC output parameter at the specified
index as the xxx Java type
• 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);
JDBC40 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
JDBC41 www.corewebprogramming.com
SQL Exception Example
try {
... // JDBC statement.
} catch (SQLException sqle) {
while (sqle != null) {
System.out.println("Message: " + sqle.getMessage());
System.out.println("SQLState: " + sqle.getSQLState());
System.out.println("Vendor Error: " +
sqle.getErrorCode());
sqle.printStrackTrace(System.out);
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
JDBC42 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
JDBC43 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) { }
}
JDBC44 www.corewebprogramming.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
JDBC45 www.corewebprogramming.com
Some JDBC Utilities
• Idea
– Performing JDBC queries and formatting output are common tasks,
so create helper classes to perform this function:
DatabaseUtilities and DBResults
• Class methods
– getQueryResults
• Connects to a database, executes a query, retrieves all the rows
as arrays of strings, and puts them inside a DBResults object
– createTable
• Given a table name, a string denoting the column formats, and
an array of strings denoting row values, this method issues a
CREATE TABLE command and then sends a series of INSERT
INTO commands for each row
– 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
JDBC46 www.corewebprogramming.com
Using JDBC Utilities
• Usage Example
DBResults results =
DatabaseUtilities.getQueryResults(driver, url,
username, password,
query, true);
out.println(results.toHTMLTable("CYAN"));
JDBC47 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
48 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?
Ad

More Related Content

What's hot (20)

Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
kamal kotecha
 
Jdbc
JdbcJdbc
Jdbc
lathasiva
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
Smita B Kumar
 
JDBC
JDBCJDBC
JDBC
Hitesh-Java
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
Dharani Kumar Madduri
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
PawanMM
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
PawanMM
 
Jdbc
JdbcJdbc
Jdbc
Indu Lata
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
Soham Sengupta
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
JAXB
JAXBJAXB
JAXB
srinivasanjayakumar
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
Akankshaji
 
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
Rohit Jain
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Pooja Talreja
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
varun arora
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
Hemo Chella
 

Similar to 22jdbc (20)

Jdbc
JdbcJdbc
Jdbc
haribee2000
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
guest04b824
 
4. Database Connectivity using JDBC .ppt
4. Database Connectivity using JDBC .ppt4. Database Connectivity using JDBC .ppt
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
SivaSankari36
 
Jdbc
JdbcJdbc
Jdbc
Jussi Pohjolainen
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
Jussi Pohjolainen
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
snopteck
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
snopteck
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
baabtra.com - No. 1 supplier of quality freshers
 
Slide Latihan JDBC
Slide Latihan JDBCSlide Latihan JDBC
Slide Latihan JDBC
Bayu Rimba
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
Prabhat gangwar
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
Dharma Kshetri
 
OOP Lecture 17-DB Connectivity-Part1.pptx
OOP Lecture 17-DB Connectivity-Part1.pptxOOP Lecture 17-DB Connectivity-Part1.pptx
OOP Lecture 17-DB Connectivity-Part1.pptx
Tanzila Kehkashan
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
nrjoshiee
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
WebStackAcademy
 
Ad

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
Adil Jafri
 
Php How To
Php How ToPhp How To
Php How To
Adil Jafri
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
Adil Jafri
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
Adil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
Adil Jafri
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
Adil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
Adil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
Adil Jafri
 
Javascript
JavascriptJavascript
Javascript
Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
Adil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
Adil Jafri
 
Html Css
Html CssHtml Css
Html Css
Adil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
Adil Jafri
 
Html Frames
Html FramesHtml Frames
Html Frames
Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
Adil Jafri
 
Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
Adil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
Adil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
Adil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
Adil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
Adil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
Adil Jafri
 
Ad

Recently uploaded (20)

The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 

22jdbc

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Introduction to JDBC
  • 2. JDBC2 www.corewebprogramming.com 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
  • 3. JDBC3 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. – API does not standardize SQL syntax • JDBC is not embedded SQL – JDBC class located in java.sql package • Note: JDBC is not officially an acronym; unofficially, “Java Database Connectivity” is commonly used
  • 4. JDBC4 www.corewebprogramming.com 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. JDBC5 www.corewebprogramming.com Oracle On-line Resources • Java Center – http://technet.oracle.com/tech/java/content.html • SQLJ & JDBC Basic Samples – http://technet.oracle.com/sample_code/tech/java/ sqlj_jdbc/content.html • JDBC Drivers – http://technet.oracle.com/software/tech/java/sqlj_jdbc/ content.html – Requires free registration • Certification – http://www.oracle.com/education/certification/
  • 6. JDBC6 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 Database JDBC Driver Manager Java Application JDBC API JDBC Driver API Vendor Specific JDBC Driver Vendor Specific ODBC Driver JDBC-ODBC Bridge Database
  • 7. JDBC7 www.corewebprogramming.com JDBC Data Types JDBC Type Java Type BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT double DOUBLE BINARY byte[] VARBINARY LONGVARBINARY CHAR String VARCHAR LONGVARCHAR JDBC Type Java Type NUMERIC BigDecimal DECIMAL DATE java.sql.Date TIME java.sql.Timestamp TIMESTAMP CLOB Clob* BLOB Blob* ARRAY Array* DISTINCT mapping of underlying type STRUCT Struct* REF Ref* JAVA_OBJECT underlying Java class *SQL3 data type supported in JDBC 2.0
  • 8. JDBC8 www.corewebprogramming.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. JDBC9 www.corewebprogramming.com JDBC: Details of Process 1. Load the driver try { Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("org.gjt.mm.mysql.Driver"); } 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 mysqlURL = "jdbc:mysql://" + host + ":" + port + "/" + dbName;
  • 10. JDBC10 www.corewebprogramming.com JDBC: Details of Process, cont. 3. Establish the Connection String username = "jay_debesee"; String password = "secret"; Connection connection = DriverManager.getConnection(oracleURL, username, password); • Optionally, look up information about the database DatabaseMetaData dbMetaData = connection.getMetaData(); String productName = dbMetaData.getDatabaseProductName(); System.out.println("Database: " + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); System.out.println("Version: " + productVersion);
  • 11. JDBC11 www.corewebprogramming.com JDBC: Details of Process, cont. 4. Create a Statement Statement statement = connection.createStatement(); 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. JDBC12 www.corewebprogramming.com JDBC: Details of Process, cont. 6. Process the Result while(resultSet.next()) { System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + 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(); – As opening a connection is expensive, postpone this step if additional database operations are expected
  • 13. JDBC13 www.corewebprogramming.com Basic JDBC Example import java.sql.*; public class TestDB { public static void main(String[] args) { // Use driver from Connect SW. String driver = "connect.microsoft.MicrosoftDriver"; try { Class.forName(driver); String url = "jdbc:ff-microsoft://" + // FastForward "dbtest.apl.jhu.edu:1433/" + // Host:port "pubs"; // Database name String user = "sa", password=""; Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); String query = "SELECT col1, col2, col3 FROM testDB"; // Execute query and save results. ResultSet results = statement.executeQuery(query);
  • 14. JDBC14 www.corewebprogramming.com Basic JDBC Example, cont. // Print column names. String divider = "-----+------+-----"; System.out.println("Col1 | Col2 | Col3n" + divider); // Print results while(results.next()) { System.out.println (pad(results.getString(1), 4) + " | " + pad(results.getString(2), 4) + " | " + results.getString(3) + "n" + divider); } connection.close(); } catch(ClassNotFoundException cnfe) { System.out.println("No such class: " + driver); } catch(SQLException se) { System.out.println("SQLException: " + se); } } ...
  • 15. JDBC15 www.corewebprogramming.com Microsoft Access Example • Northwind sample database • Northwind.mdb located in C:Program FilesMicrosoft OfficeOfficeSamples • http://office.microsoft.com/downloads/2000/Nwind2k.aspx
  • 16. JDBC16 www.corewebprogramming.com MS Access Example: Setup • Create System DSN through ODBC data source
  • 17. JDBC17 www.corewebprogramming.com 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) { System.out.println(doQuery()); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(doQuery()); } ... }
  • 18. JDBC18 www.corewebprogramming.com MS Access Example (Continued) public static String doQuery() { StringBuffer buffer = new StringBuffer(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:odbc:Northwind","",""); Statement statement = connection.createStatement(); String query = "SELECT FirstName, LastName FROM Employees"; ResultSet result = statement.executeQuery(query); buffer.append("Northwind Databasenn"); while (result.next()) { buffer.append(result.getString(1) + " " + result.getString(2) + "n"); } connection.close(); } catch (ClassNotFoundException cnfe) { buffer.append("Couldn't find class file" + cnfe); } catch (SQLException sqle) { buffer.append("SQL Exception: " + sqle); } return buffer.toString(); }
  • 20. JDBC20 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
  • 21. JDBC21 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
  • 22. JDBC22 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 • Used to check if the last getXxx read was a SQL NULL double byte int Date String float short long Time Object
  • 23. JDBC23 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 • ResultSetMetaData answers the following questions: – How many columns are in the result set? – What is the name of a given column? – Are the column names case sensitive? – What is the data type of a specific column? – What is the maximum character size of a column? – Can you search on a given column?
  • 24. JDBC24 www.corewebprogramming.com Useful MetaData Methods • getColumnCount – Returns the number of columns in the result set • 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
  • 25. JDBC25 www.corewebprogramming.com Useful MetaData Methods (Continued) • isNullable – Indicates whether storing a NULL in the column is legal – Compare the return value against ResultSet constants: columnNoNulls, columnNullable, columnNullableUnknown • 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
  • 26. JDBC26 www.corewebprogramming.com Using MetaData: Example Connection connection = DriverManager.getConnection(url, username, password); // Look up info about the database as a whole. DatabaseMetaData dbMetaData = connection.getMetaData(); String productName = dbMetaData.getDatabaseProductName(); System.out.println("Database: " + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); ... Statement statement = connection.createStatement(); String query = "SELECT * FROM fruits"; ResultSet resultSet = statement.executeQuery(query);
  • 27. JDBC27 www.corewebprogramming.com Using MetaData: Example // Look up information about a particular table. ResultSetMetaData resultsMetaData = resultSet.getMetaData(); int columnCount = resultsMetaData.getColumnCount(); // Column index starts at 1 (a la SQL) not 0 (a la Java). for(int i=1; i<columnCount+1; i++) { System.out.print(resultsMetaData.getColumnName(i) + " "); } System.out.println(); // Print results. while(resultSet.next()) { // Quarter System.out.print(" " + resultSet.getInt(1)); // Number of Apples ... }
  • 28. JDBC28 www.corewebprogramming.com Using MetaData, Result Prompt> java cwp.FruitTest dbhost1.apl.jhu.edu PTE hall xxxx oracle Database: Oracle Version: Oracle7 Server Release 7.2.3.0.0 – Production Release PL/SQL Release 2.2.3.0.0 - Production Comparing Apples and Oranges ============================ QUARTER APPLES APPLESALES ORANGES ORANGESALES TOPSELLER 1 32248 $3547.28 18459 $3138.03 Maria 2 35009 $3850.99 18722 $3182.74 Bob 3 39393 $4333.23 18999 $3229.83 Joe 4 42001 $4620.11 19333 $3286.61 Maria
  • 29. JDBC29 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
  • 30. JDBC30 www.corewebprogramming.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");
  • 31. JDBC31 www.corewebprogramming.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 number of rows a ResultSet may contain – Unless explicitly set, the number of rows are 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 SQLException
  • 32. JDBC32 www.corewebprogramming.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()
  • 33. JDBC33 www.corewebprogramming.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(); }
  • 34. JDBC34 www.corewebprogramming.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 • 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
  • 35. JDBC35 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
  • 36. JDBC36 www.corewebprogramming.com Callable Statements, cont. • Stored Procedure Syntax – Procedure with no parameters { call procedure_name } – Procedure with input parameters { call procedure_name(?, ?, ...) } – Procedure with output parameters { ? = call procedure_name(?, ?, ...) } CallableStatement statement = connection.prepareCall("{ call procedure(?, ?) }");
  • 37. JDBC37 www.corewebprogramming.com Callable Statements, cont. • Output Parameters – Register the JDBC type of each output parameter through registerOutParameter before calling execute statement.registerOutParameter(n, Types.FLOAT); – Use getXxx to access stored procedure return values
  • 38. JDBC38 www.corewebprogramming.com Callable Statements: Example String procedure = "{ ? = call isValidUser(?, ?) }"; CallableStatement statement = connection.prepareCall(procedure); statement.setString(2, username); statement.setString(3, password); statement.registerOutParameter(1, Types.BIT); statement.execute(); if (statement.getBoolean(1)) { // Valid Username, password. ... } else { // Invalid username, password. ... }
  • 39. JDBC39 www.corewebprogramming.com Useful CallableStatement Methods • CallableStatement inherits from PreparedStatement • getXxx(int parameterIndex) – Retrieves the JDBC output parameter at the specified index as the xxx Java type • 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);
  • 40. JDBC40 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
  • 41. JDBC41 www.corewebprogramming.com SQL Exception Example try { ... // JDBC statement. } catch (SQLException sqle) { while (sqle != null) { System.out.println("Message: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("Vendor Error: " + sqle.getErrorCode()); sqle.printStrackTrace(System.out); 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
  • 42. JDBC42 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
  • 43. JDBC43 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) { } }
  • 44. JDBC44 www.corewebprogramming.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
  • 45. JDBC45 www.corewebprogramming.com Some JDBC Utilities • Idea – Performing JDBC queries and formatting output are common tasks, so create helper classes to perform this function: DatabaseUtilities and DBResults • Class methods – getQueryResults • Connects to a database, executes a query, retrieves all the rows as arrays of strings, and puts them inside a DBResults object – createTable • Given a table name, a string denoting the column formats, and an array of strings denoting row values, this method issues a CREATE TABLE command and then sends a series of INSERT INTO commands for each row – 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
  • 46. JDBC46 www.corewebprogramming.com Using JDBC Utilities • Usage Example DBResults results = DatabaseUtilities.getQueryResults(driver, url, username, password, query, true); out.println(results.toHTMLTable("CYAN"));
  • 47. JDBC47 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
  • 48. 48 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?