JDBC
JDBC
Chapter 21
JDBC
In this chapter, programming concepts in Java to handle
databases are explained. How to update, modify and
execute SQL queries to a database are also discussed.
A client using ODBC API can send SQL requests to a database server and
get the results. A JDBC client does not make a direct link to a DBMS server. A
JDBC makes use of ODBC to connect to DBMS servers. The bridge between a
Java program and a database is a JDBC-ODBC driver. A conceptual structure
of using a Java API in a client to handle a database in a server is shown in
fig.21.1.
608 Programming in JAVA2
Client Server
Client
¯ -
JDBC Driver
¯ -
< ¯ - - ¯ >
Network
Fig.21.2 Type I : The JDBC-ODBC Bridge Driver
This driver is available in JDK 1.2.
In this type of driver, the JDBC requests are translated to the Call Level
Interface(CLI) of the database installed in the client machine to communicate
with a database. When the database receives the requests, they are processed
and sent back. This result in the native format of the database is converted to
JDBC format and presented to the application running in a client. This type of
driver offers a faster response than Type I drivers. The configuration of a Type
II driver is shown in fig.21.3.
Client Server
Application
¯ -
JDBC Driver
¯ -
Native Database
Libraries Database
(CLI) Server
¯ - - ¯
Network Interface Network Interface
< ¯ - - ¯ >
Network
It is similar to Type II driver. The only difference is that JDBC for server
and Native Database Libraries (CLI) is stored in the remote server.
Communication between the client and the server takes place using a JDBC
driver network protocol as shown in fig.21.4.
Client Server
Database
Server
- ¯
Native Database
Application
Libraries(CLI)
¯ - - ¯
JDBC Driver JDBC Driver
Client Side Server Side
¯ - - ¯
Network Interface Network Interface
¯ - - ¯
< JDBC Driver Network Protocol >
Fig.21.4 Type III : JDBC-Net-All-Java Driver
The advantage of this driver is that the client need not access any local
disk to get the CLI. Hence, an applet can be used to access a database over a
network.
This type of a driver is 100% Java and does not make use of any CLI
native libraries. In this type, no translation takes place. A JDBC makes a call
directly to the database. It makes use of its own DB Protocol written in Java for
network communication (fig.21.5).
Client
Server
Application
¯ -
Database
JDBC Driver Server
¯ - - ¯
Network Interface Network Interface
DB Protocol in Java
G
A java program needs a link called driver which can
understand the JDBC requests and translate them to a
format that can be understood by a database and vice
versa.
Date
DriverManager
DriverPropertyInfo
SQLPermission
Time
TimeStamp
Types
Array Blob
CallableStatement Clob
Connection DatabaseMetaData
Driver ParameterMetaData
PreparedStatement Ref
ResultSet ResultSetMetaData
Savepoint SQLData
SQLInput SQLOutput
Statement Struct
We will see the use and methods defined in some of them in the following
sections.
The following program 21.1 illustrates the steps explained above. This
program retrieves an MS-Access database stored in a table “studata”.
JDBC 613
Program 21.1
import java.sql.*;
try
{
// load the driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//establish connection
Connection conect =
DriverManager.getConnection(“jdbc:
odbc:stud_base”);
// create statment
stm = conect.createStatement();
{
System.out.println(“Class Not found error “);
}
}
}
Somasundaram K 1001 65 55 60
Magesh S 1002 85 75 95
Gomathi S 1003 93 88 97
Kumar S P 1004 90 85 95
The Connection objects are used to prepare statement objects, which are
presented in the next section 2.4.
JDBC URLs
In the above methods, the url specified refers to database URLs. The
database URLs have three components. They are :
1. ProtocolName
2. Sub-protocol
3. Subname
JDBC 615
Protocol Name
The protocol name specifies the protocol to access the database. It should
be jdbc. Therefore all JDBC URLs have the form:
jdbc : <Sub-protocol> : <subname>
Sub-protocol
Subname
The subname specifies the database server. This name depends on the
sub-protocol used. Each RDBMS has its own way of locating the source. The
subname may be network host name, database listener port number/name or
database instance name.
The important and very often used methods are those that prepare
different statements. There are basically three types of statements. They are :
Statement
PreparedStatement
CallableStatement
Statement
PreparedStatement
When SQL statements, which are large in size or are used repeatedly, a
PreparedStatement can be used, which makes the process faster.
CallableStatement
void close()
Releases the Connection object’s database and JDBC resources
void commit()
Makes all the changes made since the last commit or rollback permanent;
throws SQLException
Statement createStatement()
Creates a Statement object for sending SQL statement to the database;
throws SQLException
boolean isClosed()
Checks whether the connection is closed
void rollback()
Undoes all changes made in the current transaction
G
Only by using methods in interface, Statement,
PreparedStatement and CallableStatement objects are
created.
void close()
Releases the Statement object’s database and JDBC resources
int getMaxRows()
Returns the maximum number of rows that the result set contains
ResultSet getResultSet()
Retrieves the ResultSet generated by the execute() method
The program 21.2 is almost the same as program 21.1, but with different
methods to execute the SQL statement. In this program 21.2, we make use of a
database created in MS-Access and stored in the table “studata”. It contains 5
fields, name, rgno, comporg, java and multimedia. There are four records (4
rows) in this database.
We make the JDBC URL using this MS-Access database. For this, a
database source is to be created. This is done using the following steps:
1. Go to Control Panel
4. Then You Will Get a Dialog Box Shown Below. Select Add Button.
JDBC 619
To check whether the required jdbc data source has been created, go to
the step 4, where the ODBC Data Source Administrator appears. The name
“stu_base” is to be in the list.
JDBC 621
Program 21.2
//establish connection
Connection conect =
DriverManager.getConnection(“jdbc:
odbc:stu_base”);
// create statment
stm = conect.createStatement();
Somasundaram K 1001 65 55 60
Magesh S 1002 85 75 95
Gomathi S 1003 93 88 97
Kumar S P 1004 90 85 95
In the program 21.2, the driver is loaded using the forName() method.
The driver sun.jdbc.odbc.JdbcOdbcDriver is available in the JDK1.2. To use
other drivers, appropriate drivers are to be installed in the system. A
Connection object is created by calling getConnection() method by passing
the JDBC URL jdbc:odbc:stu_base. The string “Select * from studata” is the
SQL statement, which selects all the records in studata table. A Statement
object is created by calling the createStatement() on Connection object. The
SQL statement is executed by calling execute() method on Statement object
stm. This result created is retrieved using the getResultSet() method. This
method returns a ResultSet object. The ResultSet may contain one or more
rows of results. To get one row after another, the next() method is called.
After obtaining a record(one row), the individual fields are then obtained using
getString(“fieldname”) or getString(Column) method, which are defined in
ResultSet interface.
Comparing program 21.2 with program 21.1, you will notice that to
execute a Statement, the execute() method is used in program 21.2. To get
the result of the SQL statement, getResultSet() method is used. However, in
program 21.1, the executeQuery() method, which is equivalent to the above
two methods, is being used. In practice, executeQuery() method is more
convenient to use than using the two methods.
two fields “item” of 20 char width and “price” of type Number. Three records
are then inserted into it. The whole table is selected and printed out. The SQL
statement used to insert each record is of the form :
INSERT INTO pricelist (item, price)
VALUES(‘NeemSoap’, 12.50)
The string or char type values are placed in single quote.
Program 21.3
try
{
// load the driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//establish connection
Connection conect =DriverManager.getConnection
(“jdbc:odbc:stu_base”);
// prepare the SQL statement to create table
// named pricelist
stm = conect.createStatement();
sql = “create table pricelist (item char(20),
price number)”;
// execute the table creation sql
stm.executeUpdate(sql);
stm.executeUpdate(record3);
Item Price
In the following program 21.4, we show how to use the SQL statement,
which links two tables of MS-Access and extracts the required fields from them.
The two tables used are “studata” with fields, name, rgno, comporg, java,
multimedia and “pricelist” with fields, item and price. The SQL statement used
is:
JDBC 625
Program 21.4
try
{
// load the driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//establish connection
Connection conect =DriverManager.getConnection
(“jdbc:odbc:stu_base”);
G
by passing the SQL statements as arguments to execute(),
executeQuery() and executeUpdate() methods.
The executeQuery() method returns the results of the
query in ResultSet object.
Setting IN Parameters
In the first line an SQL statement is defined. The ? mark stands for an IN
parameter. In the second line, the PreparedStatement object is created. In
the third one, we define that the IN parameter is an integer, which is the first IN
parameter in the PreparedStatement.
boolean execute()
Executes the SQL statement in this object; one must use getResult()
method to retrieve the result
ResultSet executeQuery()
Executes the SQL statement in this object and returns ResultSet object
int executeUpdate()
Executes the SQL statement in this object; the SQL statements must be
an SQL insert, update and delete statement
ResultSetMetaData getMetaData()
Retrieves a ResultSetMetaData object that contains information about the
columns of the ResultSet object that will be returned when this object is
executed
SELECT *
FROM studata
WHERE comporg > ? AND java > ?
The IN parameters are both integers which are set using the following
Java statements:
pstm.setInt(1, 80);
pstm.setInt(2,90);
The first statement sets the first IN parameter to the value 80. The
second statement sets the second IN parameter to the value 90. The
JDBC 629
Program 21.5
import java.sql.*;
try
{
// load the driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//establish connection
Connection conect =
DriverManager.getConnection(“jdbc:
odbc:stu_base”);
while (reset.next())
System.out.println(
reset.getString(“name”) + “\t” +
reset.getInt(“rgno”) + “\t” +
reset.getInt(“comporg”) + “\t” +
reset.getInt(“java”) + “\t”
+ reset.getInt(“multimedia”));
Gomathi S 1003 93 93 97
Kumar S P 1004 90 93 95
There are 3 parameters. Let us say, the first two are IN parameter and
the third is an OUT parameter. The IN and OUT parameters are defined in the
following way:
cstm.setString(1, “Raman”);
cstm.setInt(2, 5000);
cstm.registerOutParameter(3, Types.LONGVARCHAR);
Program 21.6
conn.close();
}
}
}
The above program 21.6, makes a call to the following SQL program 21.7
stored in the Oracle database named “pdisp”.
Program 21.7
BEGIN
SELECT sregno, sname,m1,m2
INTO temp_sregno, temp_sname, temp_m1, temp_m2
FROM mark WHERE sregno=in_sregno;
out_sname := temp_sname;
out_m1 := temp_m1;
out_m2 := temp_m2;
END;
G
stored procedure with OUT parameter. A stored procedure
is passed as an argument to the prepareCall() method.
The executeQuery() and execucte() methods do not take
any argument.
The next() method moves cursor to the next row of result set. The
ResultSet interface has many methods to get the results from the result set.
Some of them are given below:
void afterLast()
Moves the cursor to the end of the result set just after the last row
void close()
Releases the object’s database
void deleteRow()
Deletes the current row of this result set
boolean first()
Moves the cursor to the first row
ResultSetMetaData getMetaData()
Returns the properties of the ResultSet object
int getRow()
Returns the current row number
636 Programming in JAVA2
Statement getStatement()
Returns the statement object which produced the ResultSet
boolean isFirst()
Checks whether the cursor is in first row
boolean isLast()
Checks whether the cursor is in the last row
boolean last()
Moves the cursor to the last row
boolean next()
Moves the cursor to the next row
boolean previous()
Moves the cursor to the previous row
After reading this chapter, you should have learned the following concepts:
Ü JDBC-ODBC Driver
Ü Creating database tables
Ü Executing SQL statements using: Statement, PreparedStatement
and CallableStatement.
In the next chapter you will learn about Servlets used in JAVAEE5(J2EE).