JDBC
JDBC
What is JDBC?
The Java API for developing Java database applications is called
JDBC.
JDBC stands for Java Database Connectivity.
JDBC is the trademarked name of a Java API that supports Java
programs that access relational databases.
JDBC provides Java programmers with a uniform interface for
accessing and manipulating a wide range of relational databases.
Using the JDBC API, applications written in the Java can execute
SQL statements, retrieve results, present data in a user-friendly
interface, and propagate changes back to the database.
The JDBC API can also be used to interact with multiple data
sources in a distributed, heterogeneous environment.
What is JDBC?
JDBC is the standard method of accessing databases from Java.
Individual database management systems require a JDBC driver to
be accessed via JDBC.
The JDBC API uses a Driver Manager and database-specific drivers
to provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to
access each data source.
The Driver Manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases.
What is JDBC?
The JDBC API is a set of Java interfaces and classes used to write Java
programs for accessing and manipulating relational databases.
Since a JDBC driver serves as the interface to facilitate communications
between JDBC and a proprietary database, JDBC drivers are database
specific.
They are normally provided by the database vendors.
You need MySQL JDBC drivers to access the MySQL database, and Oracle
JDBC drivers to access the Oracle database.
For the Access database, use the JDBC-ODBC bridge driver included in JDK.
ODBC is a technology developed by Microsoft for accessing databases on the
Windows platform.
An ODBC driver is preinstalled on Windows.
The JDBC-ODBC bridge driver allows a Java program to access any ODBC
data source.
Core JDBC Components
The JDBC API provides a number of interfaces and classes that allow to
connect to database and process the data.
The following are the most commonly used interfaces and classes:
Driver: A JDBC driver is a software component enabling a Java application
to interact with a database. To connect with individual databases, JDBC
requires drivers for each database. This interface handles the
communications with the database server. You will interact directly with
Driver objects very rarely. Instead, you use DriverManager objects, which
manages driver objects. It also abstracts the details associated with working
with Driver objects.
DriverManager: this class manages a list of database drivers. It matches
connection requests from a java application with the proper database driver
using communication subprotocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
Connection: This interface has methods for communicating with a database.
The connection object represents communication context, i.e., all
Core JDBC Components…
Statement: You use objects created from this interface to submit the SQL
statements to the database. The Statement interface contains the methods
necessary to send SQL statements to the database for execution and
return the results. In particular, you use the executeQuery() method to
execute a select statement or the executeUpdate() method to execute an
insert, update, or delete statement.
ResultSet: These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as an iterator to
allow you to move through its data. The ResultSet interface represents
rows returned from a query. It provides methods you can use to move
from row to row and to get the data of each column.
SQLException: This class handles any errors that occur in a database
application.
JDBC Drivers
A JDBC driver translates standard JDBC calls into a network or
database protocol or into a database library API call that facilitates
communication with the database.
This translation layer provides JDBC applications with database
independence.
If the back-end database changes, only the JDBC driver need be
replaced with few code modifications required.
There are four distinct types of JDBC drivers:
JDBC-ODBC bridge and ODBC driver, also called Type 1.
API.
The type 2 driver is not written entirely in Java as it interfaces with non-
is a type 2 driver.
Advantage
needed.
Disadvantages
... … … … … … …
Connecting to DB
Connecting to database involves the following steps:
Registering the driver with the DriverManager
to the database.
The first step to establishing a connection involves registering the driver class so the
class is available.
To do that, you use the forName method of the class Class, specifying the package
try {
Driver myDriver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver( myDriver );
} catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Connecting to DB…
The following table lists down popular JDBC driver names and database URL.
RDBMS JDBC driver class URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname:port/dbName
To use the JDBC-ODBC bridge in a Java, a suitable ODBC data source must be
configured.
The data source should be configured as a System DSN, not a User DSN.
The driver class name is sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is used.
The database URL used in the getConnection() statement is jdbc:odbc:dsn, where
Connecting to DB…
Connecting to Database
After you register the driver class, you can call the static getConnection
Statement createStatement (int type, Creates a Statement object that can execute an SQL
int concur) statement on the database connected by the connection.
PreparedStatement
Creates PreparedStatement object that can execute an SQL
prepareStatement( String SQL, int type,
statement on the database connected by the connection
int Concur)
CallableStatement prepareCall(String
Creates a CallableStatement object
sql, int type, int Concur)
Querying a Database…
Once you create the Statement object using one of the above
methods of Connection interface, you can now execute an SQL
statement on the database.
Statement interface provides few methods to enable programmers to
do this.
Statement Interface methods
Methods Description
Executes the select statement contained in the
ResultSet executeQuery(String sql) string parameter and returns the result data as a
ResultSet object.
Executes the insert, update, or delete statements
int executeUpdate(String sql) contained in the string parameter and returns the
result data as a ResultSet object.
Querying a Database…
The createStatement method of Connection interface has the following syntax:
Statement createStatement (int type, int concur);
The first parameter of the createStatement method specifies the type of result set
that is created, and can be one of the following:
ResultSet.TYPE_FORWARD_ONLY - the result set cannot be scrolled; its cursor
moves forward only, from before the first row to after the last row.
This is the default value.
ResultSet.TYPE_SCROLL_INSENSITIVE - the result can be scrolled; its cursor
can move both forward and backward, and it can move to an absolute position.
The result set is insensitive to changes made to the underlying data source while
it is open.
It contains the rows that satisfy the query at either the time the query is executed
or as the rows are retrieved.
ResultSet.TYPE_SCROLL_SENSITIVE - the result can be scrolled; its cursor
can move both forward and backward, and it can move to an absolute position.
The result set reflects changes made to the underlying data source while the
Querying a Database…
The second parameter is the concurrency of a ResultSet object.
The concurrency of a ResultSet object determines what level of
update functionality is supported.
This indicates whether the result set is read-only or updatable, and
can be one of the following:
ResultSet.CONCUR_READ_ONLY - creates a read-only result
Method Description
void cancelRowUpdates() Cancels the updates made to the current row in this ResultSet object.
Deletes the current row from this ResultSet object and from the
void deleteRow()
underlying database.
Inserts the contents of the insert row into this ResultSet object and
void insertRow()
into the database.
Moves the cursor to the remembered cursor position, usually the
void moveToCurrentRow()
current row.
void moveToInsertRow() Moves the cursor to the insert row.
void refreshRow() Refreshes the current row with its most recent value in the database.
This method cannot be called when the cursor is on the insert row.
try {
rs.absolute(3);
rs.deleteRow();
}catch (SQLException e) {
out.println(e.getMessage());
Updating Database…
Updating Rows
For a result set to be updated, it must have been produced by a
Statement object created with a concurrency type of
ResultSet.CONCUR_UPDATABLE.
JDBC provides updateXXX() methods, where XXX is the JDBC
data type, similar to the existing getXXX() methods.
These methods take a column number or column name parameter,
and a value parameter.
Update by Column name or index description
updateBoolean (String colname, boolean value) Updates the designated column with a boolean value. The updater methods are used
updateBoolean(int colIndex, boolean value) to update column values in the current row or the insert row.
updateDate(String colname, Date value) Updates the designated column with a java.sql.Date value. The updater methods are
updateDate(int colIndex, Date value) used to update column values in the current row or the insert row.
updateDouble (String colname, double value) Updates the designated column with a double value. The updater methods are used
updateDouble(int colIndex, double value) to update column values in the current row or the insert row.
updateFloat(String colname, float value) Updates the designated column with a float value. The updater methods are used to
updateFloat(int colIndex, float value) update column values in the current row or the insert row.
updateInt(String colname, int value) Updates the designated column with an int value. The updater methods are used to
updateInt(int colIndex, int value) update column values in the current row or the insert row.
updateLong(String colname, long value) Updates the designated column with a long value. The updater methods are used to
updateLong(int colIndex, long value) update column values in the current row or the insert row.
updateShort(String colname, short value) Updates the designated column with a short value. The updater methods are used to
updateShort(int columnIndex, short value) update column values in the current row or the insert row.
updateBigDecimal (String colname, BigDecimal value) Updates the designated column with a java.sql.BigDecimal value. The updater
updateBigDecimal(int colIndex, BigDecimal value) methods are used to update column values in the current row or the insert row.
updateString(String colname, value) Updates the designated column with a String value. The updater methods are used to
updateString(int String colIndex, String value) update column values in the current row or the insert row.
updateBlob(String columnName, Blob x) Updates the designated column with a java.sql.Blob value.The updater methods are
updateBlob(String columnIndex, Blob x) used to update column values in the current row or the insert row.
updateByte(String columnName, byte x) Updates the designated column with a byte value. The updater methods are used to
updateByte(String columnIndex, byte x) update column values in the current row or the insert row.
updateBytes(int columnName, byte x[]) Updates the designated column with a byte array value. The updater methods are
updateBytes(int columnIndex, byte x[]) used to update column values in the current row or the insert row.
Updating Database…
The following example illustrates how to update the current row of
the ResultSet:
rs.updateString(“lastname”,”William”);
rs.updateString(“sex”, “female”);
rs.updateInt(“phone”, 3456218769)
rs.updateString(“email”, “[email protected]”);
rs.updateRow();
Updating Database…
Inserting New Rows
New rows can be added to the result set and the underlying table with insertRow().
This involves a special cursor position known as the insert row.
You can add/ insert data into the insert row using the updateXXX() methods
shown above.
The following example illustrates how this works:
rs.moveToInsertRow();
rs.updateString(“ID”, “1256/07”);
rs.updateString(“firstname”, “David”);
rs.updateString(“middlename”, “Jacques”);
rs.updateString(“lastname”, “George”);
rs.updateString(“sex”, “Male”);
rs.updateString(“email”, “[email protected]”);
rs.updateInt(“telephone”, 8954578693567);
rs.insertRow();
PreparedStatement Object
The PreparedStatement interface extends the Statement interface which gives
you added functionality with many advantages over a generic Statement
object.
This statement gives you the flexibility of supplying arguments dynamically.
The Statement interface is used to execute static SQL statements that contain
no parameters.
The PreparedStatement interface is used to execute a precompiled SQL
statement with or without parameters.
Since the SQL statements are precompiled, they are efficient for repeated
executions.
The main feature of a PreparedStatement object is that it is given an SQL
statement when it is created.
The advantage to this is that the SQL statement is sent to the DBMS right
away, where it is compiled.
PreparedStatement Object…
As a result, the PreparedStatement object contains an SQL statement
that has been precompiled.
So, when PreparedStatement is executed, the DBMS can just run the
PreparedStatement SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL
statements with no parameters, you probably use them most often
for SQL statements that take parameters.
The advantage of using SQL statements that take parameters is that
you can use the same statement and supply it with different values
each time you execute it.
Besides, PreparedStatement can help to avoid SQL injection attack.
Attaching parameters later on reduces the risk of malicious user
performing SQL injection attack on the program.
PreparedStatement Object…
To create PreparedStatement object, call the prepareStatement method of
Connection interface.
PreparedStatement prepareStatement(String sql) – creates a PreparedStatement
object for sending parameterized SQL statements to the database. It throws
SQLException.
PreparedStatement prepareStatement(String sql, int resultType, int concurrency) –
creates a PreparedStatement object that will generate ResultSet objects with the
given type and concurrency.
resultType – is a result set type; one of TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE, or TYPE_SCROLL_SENSITIVE.
concurrency – is a concurrency type; one of CONCUR_READ_ONLY or
CONCUR_UPDATABLE.
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) - creates
a PreparedStatement object that has the capability to retrieve auto-generated keys.
The given constant tells the driver whether it should make auto-generated keys
available for retrieval.
This parameter is ignored if the SQL statement is not an INSERT statement, or an
SQL statement able to return auto-generated keys.
autoGeneratedKeys – one of Statement.RETURN_GENERATED_KEYS or
PreparedStatement Object…
All parameters in JDBC are represented by the ? symbol, which is
known as the parameter marker.
You must supply values for every parameter before executing the
SQL statement.
The setXXX() methods bind values to the parameters, where XXX
represents the Java data type of the value you wish to bind to the
input parameter.
If you forget to supply the values, you will receive an
SQLException.
Each parameter marker is referred to by its ordinal position.
The first marker represents position 1, the next position 2, and so
forth.
This method differs from that of Java array indices, which start at 0.
Method description
Sets the designated parameter to the given Java String value. The driver converts this to
setString(int paramIndex, String value) an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to
the driver's limits on VARCHAR values) when it sends it to the database.
Sets the designated parameter to the given Java double value.The driver converts this to
setDouble(int paramIndex, double x)
an SQL DOUBLE value when it sends it to the database.
Sets the designated parameter to the given Java float value. The driver converts this to an
setFloat(int paramIndex, float x)
SQL REAL value when it sends it to the database.
Sets the designated parameter to the given Java long value. The driver converts this to an
setLong(int paramIndex, long x)
SQL BIGINT value when it sends it to the database.
Sets the designated parameter to the given Java int value. The driver converts this to an
setInt(int paramIndex, int x)
SQL INTEGER value when it sends it to the database.
Sets the designated parameter to the given Java short value. The driver converts this to an
setShort(int paramIndex, short x)
SQL SMALLINT value when it sends it to the database.
Sets the designated parameter to the given Java byte value. The driver converts this to an
setByte(int paramIndex, byte x)
SQL TINYINT value when it sends it to the database.
Sets the designated parameter to the given java.math.BigDecimal value. The driver
setBigDecimal(int paramIndex, BigDecimal x)
converts this to an SQL NUMERIC value when it sends it to the database.
Sets the designated parameter to the given Java boolean value. The driver converts this to
setBoolean(int paramIndex, boolean x)
an SQL BIT or BOOLEAN value when it sends it to the database.
Sets the designated parameter to the given java.sql.Date value. The driver converts this to
setDate(int paramIndex, Date x)
an SQL DATE value when it sends it to the database.
Sets the designated parameter to the given java.sql.Blob object. The driver converts this
setBlob (int paramIndex, Blob x)
to an SQL BLOB value when it sends it to the database.
Sets the designated parameter to the given java.sql.Array object. The driver converts this
setArray (int paramIndex, Array x)
to an SQL ARRAY value when it sends it to the database.
setNull(int paramIndex, int sqlType) Sets the designated parameter to SQL NULL.
PreparedStatement Object…
All of the Statement object's methods for interacting with the database
execute(), executeQuery(), and executeUpdate() also work with the
PreparedStatement object.
However, the methods are modified to use SQL statements that can take
input parameters.
Method Description
void clearParameters() Resets all of the PreparedStatment’s query parameters
Runs the prepared query against the database; this
boolean execute() method is used primarily if multiple ResultSets are
expected.
ResultSet executeQuery() Executes the prepared query.
Executes the prepared query; this method is used for
queries that do not produce a ResultSet (such as Update).
Int executeUpdate()
It returns the number or rows affected or 0 if nothing is
returned by the SQL command
PreparedStatement pstmt = null;
Connection con = null;
void insert() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "vertrigo");
String SQL = "INSERT INTO student VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, "4536/05");
pstmt.setString(2, "Anna");
pstmt.setString(3, "Tom");
pstmt.setString(4, "Bill");
pstmt.setString(5, "female");
pstmt.setDate(6, new Date(95,10, 25));
pstmt.setInt(7, 748538857);
pstmt.setString(8, "[email protected]");
int suc = pstmt.executeUpdate();
if (suc == 1)
System.out.print("Data inserted");
else
System.out.print("Data insertion failed");
}catch (Exception e) {
System.out.print("Error: " + e.getMessage());
}
}
PreparedStatement Object…
Once a PreparedStatement is prepared, it can be reused again and again.
You reuse a PreparedStatement by setting new values for the parameters
and then execute it again.
String sql = "update student set firstname=? , middlename=?, lastname=?
where id=?";
PreparedStatement pstatement = connection.prepareStatement(sql);
pstatement.setString(1, "Gary");
pstatement.setString(2, "Larson");
pstatement.setString(3, "Walter");
pstatement.setString (4, "123 ");
int rf = pstatement.executeUpdate();
pstatement.setString(1, "Chan");
pstatement.setString(2, "Lee");
pstatement.setString(3, "Huang");
pstatement.setString(4, " 456 ");
Batch Updating
JDBC 2.0 introduced the capability to submit a group of update statements
to be executed as a batch.
Batch Processing allows you to group related SQL statements into a batch
and submit them with one call to the database.
In some cases, this can represent a significant performance improvement.
When you send several SQL statements to the database at once, you reduce
the amount of communication overhead, thereby improving performance.
A batch update is a batch of updates grouped together, and sent to the
database in one "batch", rather than sending the updates one by one.
Sending a batch of updates to the database in one go, is faster than sending
them one by one, waiting for each one to finish.
There is less network traffic involved in sending one batch of updates, and
the database might be able to execute some of the updates in parallel.
The speed up compared to executing the updates one by one, can be quite
big.
Batch Updating…
JDBC drivers are not required to support this feature.
You should use the DatabaseMetaData.supportsBatchUpdates() method to
determine if the target database supports batch update processing.
The method returns true if your JDBC driver supports this feature.
The methods used in connection with batch updates are these:
void clearBatch() - resets a batch to the empty state.
It empties this Statement object's current list of SQL commands.
It throws SQLException.
void addBatch(String sql) - adds the given SQL command to the batch.
It throws SQLException if a database access error occurs.
pstatement.setString(1, "345/06");
pstatement.setString(2, "Tesfaye");
pstatement.setString(3, "Mekonen");
pstatement.setString(4, "Getahun");
pstatement.addBatch();
pstatement.setString(1, 102);
pstatement.setString(2, “Tesfaye");
pstatement.setString(3, “Bekele");
pstatement.setString(4, “Abebe”);
pstatement.addBatch();
Retrieving Metadata
JDBC provides the DatabaseMetaData interface for obtaining database-wide
information.
It provides ResultSetMetaData interface for obtaining information on the
specific ResultSet.
A. DatabaseMetadata
A connection provides access to database metadata information that describes
as a whole.
There are many methods within the interface, such as whether or not
connection.close();
}
}
Retrieving Metadata…
B. Result Set Metadata
The ResultSetMetaData interface describes information pertaining to the
result set.
A ResultSetMetaData object can be used to find the types and properties
of the columns in a ResultSet.
To obtain an instance of ResultSetMetaData, use the getMetaData method
on a result set like this:
ResultSetMetaData rsMetaData = resultSet.getMetaData();
ResultSetMetaData defines a number of methods that returns information
about the result set.
For example, you can use the getColumnCount() method to find the
number of columns in the result and the getColumnName(int) method to
get the column names.
Retrieving Metadata…
Method Description
int getColumnCount() This returns the number of columns in this ResultSet object.
Indicates whether the designated column is automatically
boolean isAutoIncrement(int col)
numbered.