Professional Documents
Culture Documents
JDBC
Introduction:
JDBC stands for Java Database Connectivity, which is a standard Java API to connect and
execute query with the database.
The JDBC library includes APIs for each of the tasks associated with database usage:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
Praveen Banasode
JDBC
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.
JDBC Drivers:
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API Partially java driver
3. JDBC-Net Pure-Java driver
4. Native Protocol Pure-Java driver
1. JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
Advantages:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC
function calls.
The ODBC driver needs to be installed on the client machine.
Praveen Banasode
JDBC
2.
Advantage:
Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
3. JDBC-Net Pure-Java driver
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in
java.
Advantage:
No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
Praveen Banasode
JDBC
Disadvantages:
4.
Advantage:
Praveen Banasode
JDBC
Loading a Driver
The first step develop a JDBC application is to load and register the required driver using the driver
manager. you load and register a driver:
Programmatically:
o Using the forName() method
o Using the registerDriver() method
o Using the forName() method The forName() method is available in the java.lang.Class class.
The forName() method loads the JDBC driver and registers the driver with driver manager.
Syntax:
Class.forName(<driver_name>);
you can load the JDBC-ODBC driver using the following method call:
o Using the registerDriver() method create an instance of the Driver class to load a JDBC
driver.
Praveen Banasode
JDBC
Syntax:
Driver d = new <driver name>
Use the following statement to create an instance of the Driver class
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
once you have created the Driver object, call the registerDriver() method to register it with the
DriverManager.
DriverManager.registerDriver(d);
Connecting to a Database
create an object of the Connection interface to establish a connection of the Java application with a
database. Create multiple Connection objects in a Java application to access and retrieve data from
multiple databases. The DriverManager class provides the getConnection() method to create a
Connection object.
The getConnection() method is an overloaded method that has the following three forms:
1. Connection getConnection(String <url>): Accepts the JDBC URL of the database, which
you need to access, as a parameter.
String url = jdbc:odbc:MyDataSource;
Connection con = DriverManager.getConncetion(url);
The syntax for aJDBC URL that is passed as a parameter to the getConnection()
method is
<protocol>:<subprotocol>:<subname>
A JDBC URL has the following three components:
Protocol name: Indicates the name of the protocol that is used to access a database. In
JDBC, the name of the access protocol is always jdbc.
Sub-protocol name: Indicates the mechanism to retrieve data from a database.
Subname: Indicates the Data Source Name(DSN) that contains database information, such
as the name of a database, location of the database server, user name, and password to access
a database server.
Praveen Banasode
JDBC
ResultSet executeQuery(String str): Executes an SQL statement and returns a single object
of the type, ResultSet. The executeQuery() method should be used when you need to retrieve
data from a database table using the SELECT statement.
Syntax:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(<SQL statement>);
The executeQuery() method executes an SQL statement and the result retrieved from a
database is stored in rs, the ResultSet object.
int executeUpdate(String str) : Executes the SQL statements and returns the number of data
rows that are affected after processing the SQL statement. When you to modify data in a
database table using the Data Manipulation Language(DML) statements, INSERT,
DELETE, an UPDATE you can use the executeUpdate() method
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(<SQL statement>);
The executeUpdate() method executes an SQL statement and number of rows affected in a
database is stored in count, the int type variable.
Praveen Banasode
JDBC
Boolean execute(String str): Executes an SQL statement and returns a Boolean value. You can use
this method when the type of SQL statement passed as parameter is not known or when the
statement being executed returns a result set or an update count.
The execute() method returns true if the result of the SQL statement is an object of ResultSet and
false if it is an update count.
Syntax:
Statement stmt = con.creteStatement();
stmt.execute(<SQL stement>);
The SQLException class contains various methods that provide error information. The methods
in the SQLException class are:
int getErrorCode() : Returns the error code associated with error occurred.
String getSQLState(): Returns X/OPEN error code
SQLException getNextException() : Returns the next exception in the chain of
exception.
Following code snippet to catch SQLException:
try
{
String str = DELETE FROM student WHERE st_id=123;
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
}
catch(SQLException sqlExceptionObject)
{
System.out.println(Display Error Code);
System.out.println(SQL Exception+sqlExceptionObject.getErrorCode());
}
Praveen Banasode
JDBC
If the DELETE statement at running throws an SQLException then it is handled using the try
catch block. The sqlExceptionObject is an object of the SQLException class and is used to invoke
the getErrorCode() method.
You can use the DML statements, INSERT, UPDATE, and DELETE, in Java application to modify
the data stored in the database tables.
You can also use the Data Definition Language(DDL) statements, CREATE, ALTER, and DROP, in
Java application to define or change the structure of database objects.
Querying a table
Inserting rows in a table
Updating rows in a table
Deleting rows from a table
Creating a table
Altering and dropping a table
Querying a table Retrieve data from a table using the SELECT statement. The SELECT
statement executed using the executeQuery() method.
String str = SELECT * FROM student;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(str);
Inserting Rows in a Table The executeUpdate() method enables you to add rows in a
table.
String str = INSERT INTO
student(st_id,st_name,address,city,state)VALUES(123,Ram,801 street, 2nd
Cross,Belagavi,Karnataka);
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
Praveen Banasode
JDBC
Updating Rows in a table The existing information in a table can be modified using the
UPDATE statement.
String str = UPDATE student SET address = 10932 First AV WHERE st_id =
123;
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
The statement object executes this statement using the executeUpdate()
Deleting Rows from a Table You can delete existing information from a table using the
DELETE statement.
String str = DELETE FROM student WHERE st_id = 999
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
Str contains the DELETE statement that you need to send to a database. The Statement object
executes this statement using the executeUpdate().
The str String contains the CREATE TABLE statement to create the MyProduct table. The
execute() method is used to process the CREATE TABLE statement.
Altering and Dropping a Table DDL provides the ALTER statement to modify the
definition of database object.
String str = ALTER TABLE MyProduct
+ ADD quantity integer;
Statement stmt = con.createStatement();
stmt.execute(str);
DDL provides the DROP statement to drop an object from a database
String str = DROP TABLE MyProduct
Statement stmt = con.createStatement();
stmt.execute(str);
Praveen Banasode
10
JDBC
When you execute a query to retrieve data from a table using a Java application, the output of
the query is stored in a ResultSet object in a tabular format.
A ResultSet object maintains a cursor that enables you to move through the rows stored in a
ResultSet object.
By default, the ResultSet object maintains a cursor that moves in the forward direction only
It moves from the first row to the last row in the ResultSet.
The cursor in the ResultSet object initially points before the first row.
TYPE_FORWARD_ONLY
Praveen Banasode
Description
Specifies that the cursor of the ResultSet object is scrollable
and it reflects the changes in the data made by other users.
Specifies that the cursor of the ResultSet object is scrollable
and it does not reflect changes in the data made by other
users
Specifies that the cursor of the ResultSet object is moves in
forward direction only from the first row to the last row.
11
JDBC
The following lists various fields of the ResultSet interface that you can use to specify different
concurrency modes of the result sets:
ResultSet Fields
CONCUR_READ_ONLY
CONCUR_UPDATABLE
Description
Specifies the concurrency mode that does not allow you to update
the ResultSet object
Specifies the concurrency mode that allows you to update the
ResultSet object.
The following lists various fields of the ResultSet interface that you can use to specify different
cursor states of result sets:
ResultSet Fields
HOLD_CURSOR_OVER_COMMIT
CLOSE_CURSOR_AT_COMMIT
Description
Specifies that a ResultSet object should not be closed after
data is committed to the databse.
Specifies that a ResultSet object should be closed after
data is committed to the database.
statement createStatement(): Does not accept any parameter. This method creates a default
ResultSet object that only allows forward scrolling.
statement createStatement(int, int): Accepts two parameters. The first parameter indicates
the ResultSet type that determines whether or not, a result set cursor can move backward.
The second parameter indicates the concurrency mode for the result set that determines
whether the data in the result set can be updated.
This method creates a ResultSet object with the given type and concurrency.
Praveen Banasode
12
JDBC
13
JDBC
Similarly, you can move the result set, cursor to the last row in the result set using the last() method.
If the result set cursor is at the first row and you want to scroll to the fourth row, you should enter 4
as a parameter when you call the absoulute() method.
System.out.println(Using absolute() method);
rs.absolute(4);
int rowcount = rs.getRow();
System.out.println(RowNum should be 4 +rowcount);
JDBC allows you to create an updatable result set that enables you to modify the rows in the result
set. The following table lists some of the methods used with updatable result set:
Method
void updateRow()
void insertRow()
void deleteRow()
void updateString()
void updateInt()
Description
Updates a row of the current ResultSet object and the underlying
database table.
Inserts a row in the current ResultSet object and the underlying
database table
Deletes a row from the current ResultSet object and the underlying
database table.
Updates the specified column with the given string value
Updates the specified column with the given int value.
ex:
Statement stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(Select st_id, city From student Where
st_id=123);
rs.next();
rs.updateString(state,NY);
rs.updateString(city,Belagavi);
rs.updateRow();
In the preceding code snippet, the row is retrieved from the student table where student id is
123. In the retrieved row, the value in the state column is changed to NY and the value in the
city column is changed to Belagavi.
Praveen Banasode
14
JDBC
The PreparedStatement interface is derived from the Statement interface and is available in
the java.sql package.
The PreparedStaement object allows you to pass runtime parameters to the SQL statements
to query and modify the data in a table.
The PreparedStaement objects are compiled and prepared only once by JDBC. The future
invocation of the PreparedStatement object does not recompile the SQL statements. This
helps in reducing the load on the database server and thus improving the performance of the
application.
ResultSet executeQuery() : Executes a SELECT statement and returns the result in a Result
in a ResultSet object.
int executeUpdate(): Executes an SQL statement, INSERT, UPDATE, or DELETE and
returns the count of rows affected.
boolean execute(): Executes an SQL statement and returns a Boolean value.
Consider you have to retrieve the details of an author by passing author id at runtime.
The SQL statement to write a parameterized query is:
SELECT * FROM authors WHERE au_id = ?
To submit such parameterized query to a database from an application, you need to create a
PreparedStatement object using the prepareStaement() method of the Connection object. Use the
following method call to prepare an SQL statement that accepts values at runtime:
stat = con.prepareStatement(SELECT * FROM authors WHERE au_id = ?);
Praveen Banasode
15
JDBC
The prepareStatement() method of the Connection object takes an SQL statement as a parameter.
The SQL statement can contain ? symbol as placeholder that can be replaced by input parameters
at runtime.
Before executing the SQL statement specified in the PreparedStatement object, you must set the
value of each ? parameter. This is done by calling an appropriate setXXX() method, Where XXX is
the data type of the parameter. For Example
stat.setString(1, 1001);
ResultSet result = stat.executeQuery();
The first parameter of the setString() method specifies the index value of ? placeholder and second
parameter is used to set 1001 as the value of ? placeholder.
stat.setString(1,aid.getText());
ResultSet result = stat.executeQuery();
setString() method is used to set the value of the ? placeholder with value retrieved at runtime from
the aid textbox of the user interface.
The PreparedStatement interface provides various methods to set the value of placeholders for the
specific data types.
Method
void setByte(int index, byte val)
void setBytes(int index, byte[] val)
void setBoolean(int index, boolean val)
void setDouble(int intdex, double val)
void setInt(int index, int val)
void setLong(int index, long val)
void setFloat(int index, float val)
void setShort(int index, short val)
void setString(int index, String val)
Description
Sets the Java byte type value for the parameter corresponding
to index passed as a parameter.
Sets the Java byte type array for the parameter corresponding
to the index passed as parameter
Sets the Java boolean type value for the parameter
corresponding to index passed as a parameter.
Sets the Java double type value for the parameter
corresponding to index passed as a parameter.
Sets the Java int type value for the parameter corresponding
to index passed as a parameter.
Sets the Java long type value for the parameter corresponding
to index passed as a parameter
Sets the Java float type value for the parameter corresponding
to index passed as a parameter.
Sets the Java short type value for the parameter
corresponding to index passed as a parameter.
Sets the Java String type value for the parameter
corresponding to index passed as a parameter.
Retrieving Rows
To retrieve books written by an author from the titles table using the PreparedStatement object:
String str = Select * From titles Where au_id = ?
PreparedStatement ps = con.prepareStatement(str);
Praveen Banasode
16
JDBC
ps.setString(1,1001);
ResultSet rs = ps.executeQuery();
Inserting Rows
Create a PreparedStatement object that inserts a row into authors table by passing authors data at
runtime.
String str = INSERT INTO authors (au_id, au_fname, au_lname) VALUES (?,?,?);
PreparedStatement ps = con.prepareStatement(str);
ps.setString(1,1001);
ps.setString(2,Abraham);
ps.setString(3,White);
int rt = ps.executeUpdate();
The INSERT statement is executed using the executeUpdate() method, which returns an integer
value specifying the number of rows inserted into the table.
Praveen Banasode
17
JDBC
Praveen Banasode
18
JDBC
The update count is the total number of rows affected when an SQL statement is
processed.
Praveen Banasode
19
JDBC
QUESTIONS
1.
Discuss on the various steps of using JDBC to connect with a database with code snippet
2.
3.
4.
5.
6.
7.
What is scrollable and updatable resultset? List out the methods for scrolling cursor within
the resultset rows.
8.
9.
Write down the steps for JDBC process and explain them with a Java JDBC program
10.
Give the syntax of inserting a row into Student table with fields name, usn, and result.
11.
Write a JDBC program to select columns from a employee table using statement object.
Praveen Banasode
20