Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
27 views69 pages

Chapter 4

The document discusses remote database access and the use of JDBC (Java Database Connectivity) for Java applications to communicate with databases using SQL statements. It explains the types of JDBC drivers, including the JDBC-ODBC bridge and the differences between Type 1, Type 2, Type 3, and Type 4 drivers, emphasizing the advantages of pure Java drivers. Additionally, it outlines the process of connecting to an ODBC data source, managing SQL transactions, and the role of the DriverManager in establishing database connections.

Uploaded by

birhadepranusha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views69 pages

Chapter 4

The document discusses remote database access and the use of JDBC (Java Database Connectivity) for Java applications to communicate with databases using SQL statements. It explains the types of JDBC drivers, including the JDBC-ODBC bridge and the differences between Type 1, Type 2, Type 3, and Type 4 drivers, emphasizing the advantages of pure Java drivers. Additionally, it outlines the process of connecting to an ODBC data source, managing SQL transactions, and the role of the DriverManager in establishing database connections.

Uploaded by

birhadepranusha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Advance Java Programming (17625)

Chapter – 04 Marks: 20

Interaction with Databases

Remote Database Access:

Most useful databases are accessed remotely. In this way, shared access to the
database can be provided to multiple users at the same time. For example, you can have a
single data base server that is used by all employees in the accounting department.
In order to access databases remotely, users need a database client. A database
clientCommunicates to the database server on the user's behalf, It provides the user with
theCapability to update with new information or to retrieve information from the database.
InThis book, you'll learn to write Java applications and applets that serve as database
clients.Your database clients talk to database servers using SQL statements (See Figure )

4.1 ODBC and JDBC drivers:


Database clients use database drivers to send SQL statements to database servers and
toreceive result set and other responses from the servers. JDBC drivers are used by

1
Advance Java Programming (17625)

Javaapplications and applets to communicate with database servers. Officially, Sun says
thatJDBC is an acronym that does not stand for anything. However, it is associated with
"Javadatabase connectivity".

Microsoft's ODBC:
Many database servers use vendor-specific protocols. This means that a database
client has tolearn a new language to talk to a different database server. However, Microsoft
established acommon standard for communicating with databases, called Open Database
Connectivity(ODBC). Until ODBC, most database clients were server-specific. ODBC
drivers abstractaway vendor-specific protocols, providing a common application-
programming interface to database clients. By writing your database clients to the ODBC
API, you enable yourprograms to access more database servers. (See Figure)

Comes JDBC:
JDBC provides a common database-programming API for Java programs. However,
JDBCdrivers do not directly communicate with as many databases using ODBC. In fact, one
of thefirst JDBC drivers was the JDBC-ODBC bridge driver developed by JavaSoft and
Intersolv.
Why did JavaSoft create JDBC? What boil down to the simple fact that ODBC is a
bettersolution for Java applications and applets:
 ODBC is a C language API, not a Java (object-oriented and C is not) API. C uses
pointersand other "dangerous" programming constructs that Java does not support. A
Javaversion of ODBC would require a significant rewrite of the ODBC API.

2
Advance Java Programming (17625)

 ODBC drivers must be installed on client machines. This means that applet access
todatabases would be constrained by the requirement to download and install a JDBC
driver. A pure solution allows JDBC drivers to be automatically downloaded and
installed along with applet. This greatly simplifies database access for applet users.
Since the release of the JDBC API, a number of JDBC drivers have been developed.
These drivers provide varying levels of capability. JavaSoft has classified JDBC
drivers into the following four types:
1. JDBC-ODBC Bridge plus ODBC driver:
This driver category refers to the original JDBCODBCbridge driver. The JDBC-ODBC
bridge driver uses Microsoft's ODBC driver tocommunicate with database servers. It is
implemented in both binary code and Java andmust be preinstalled on a client computer
before it can be used.JavaSoft created the Java-ODBC bridge driver as a temporary solution
to databaseconnectivity until suitable JDBC drivers were developed. The JDBC-ODBC
bridge drivertranslates the JDBC API into the ODBC API and it used with an ODBC driver.
The JDBCODBCbridge driver is not an elegant solution, but it allows Java developers to use
existing ODBC drivers. (See Figure). The JDBC-ODBC Bridge lets Java clients talk to
databases viaODBC drivers.

2. Native-API partly Java driver (also called Type 2 Driver ):


This driver category consistsof drivers that talk to database servers in the server's native
protocol. For example, anOracle driver would speak SQLNet, while a DB2 driver would use
an IBM databaseprotocol. These drivers are implemented in a combination of binary code
and Java, andthey must be installed on client machines.

3
Advance Java Programming (17625)

A type 2 JDBC driver uses a vendor-specific protocol and must be installed on


clientmachines.

3. JDBC-Net pure Java driver:


This driver category consists of pure Java drivers that speak a standard network protocol
(such as HTTP) to a database access server. The database access server then translates the
network protocol into a vendor-specific database protocol (possibly using an ODBC driver).

A type 4 JDBC driver is a pure Java driver that uses a vendor-specific protocol to talk
todatabase servers.

4
Advance Java Programming (17625)

Of the four types of drivers, only Type 3 and Type 4 are pure Java drives. This is
important tosupport zero installation for applets. The Type 4 driver communicates with the
database serverusing a vendor-specific protocol, such as SQLNet. The Type 3 driver make as
use of aseparate database access server. It communicates with the database access server
using astandard network protocol,such as HTTP. The database access server communicates
withdatabase servers using vendor-specific protocols or ODBC drivers. The IDS JDBC
driverConnect to Databases with the java.sql.Package

JDBC:

JDBC is a Java database connectivity API that is a part of the Java Enterprise APIs
from JavaSoft. From a developer's point of view, JDBC is the first standardized effort to
integraterelational databases with Java programs. JDBC has opened all the relational power
that canbe mustered to Java applets and applications.

Model:
JDBC is designed on the CLI model. JDBC defines a set of API objects and methods
to interactwith the underlying database. A Java program first opens a connection to a
database, makes astatement object, passes SQL statements to the underlying DBMS through
the statementobject, and retrieves the results as well as information about the result sets.
Typically, theJDBC class files and the Java applet reside in the client. To minimize the
latency duringexecution, it is better to have the JDBC classes in the client.As a part of JDBC,
Java Soft also delivers a driver to access ODBC data sources from JDBC.This driver is
jointly developed with Intersolv and is called the JDBC-ODBC Bridge. TheJDBC-ODBC
Bridge is implemented as the JdbcOdbc.class and a native library to access theODBC driver.

5
Advance Java Programming (17625)

For the Windows platform, the native library is a DLL (JDBCODBC.DLL).As JDBC is close
to ODBC in design, the ODBC Bridge is a thin layer over JDBC. Internally,this driver maps
JDBC methods to ODBC calls and, thus, interacts with any available ODBCdriver. The
advantage of this bridge is that now JDBC has the capability to access almost alldatabases, as
ODBC drivers are widely available. The JDBC-ODBC Bridge allows JDBCdriver to be used
as ODBC drivers by converting JDBC method calls into ODBC functioncalls.

Drivers:
Using the JDBC-ODBC Bridge requires three things:
The JDBC-ODBC bridge driver included with Java2:
sun.jdbc.odbc.JdbcOdbcDriver an ODBC driver.

An ODBC data source that has been associated with the driver using software such as
theODBC Data Source Administrator.ODBC data sources can be set up from within some
database programs. When a newdatabase file is created in any ODBC supported application
system, users have the option ofassociating it with an ODBC driver.
All ODBC data sources must be given a short descriptive name. This name will be
usedinside Java programs when a connection is made to the database that the source refers to.
In
Windows environment, once an ODBC driver is selected and the database is created, theywill
show up in the ODBC Data Source Administrator.

Two-tier and Three-tier Models:

The JDBC API supports both two-tier and three-tier models for database access. In
the two-tier model, a Java applet or application talks directly to the database. This requires a
JDBC driver that can communicate with the particular database management system being
accessed. A user's SQL statements are delivered to the database, and the results of those
statements are sent back to the user. The database may be located on another machine to
which the user is connected via a network. This is referred to as a client/server configuration,
with the user's machine as the client, and the machine housing the database as the server. The
network can be an intranet, which, for example, connects employees within a corporation, or
it can be the Internet.

6
Advance Java Programming (17625)

In the three-tier model, commands are sent to a "middle tier" of services, which then
send SQL statements to the database. The database processes the SQL statements and sends
the results back to the middle tier, which then sends them to the user. MIS directors find the
three-tier model very attractive because the middle tier makes it possible to maintain control
over access and the kinds of updates that can be made to corporate data. Another advantage is
that when there is a middle tier, the user can employ an easy-to-use higher-level API which is
translated by the middle tier into the appropriate low-level calls. Also, in many cases the
three-tier architecture can provide performance advantages.

Until now the middle tier has typically been written in languages such as C or C++,
which offer fast performance. However, with the introduction of optimizing compilers
translating Java bytecode into efficient machine-specific code, it is becoming practical to
implement the middle tier in Java. This is a big plus, making it possible to take advantage of
Java's robustness, multi-threading, and security features.

7
Advance Java Programming (17625)

4.2 Connecting to an ODBC Data Source:


Java application that uses a JDBC-ODBC bridge to connect to a database file either a
dbase,Excel, FoxPro, Access, SQL Server, Oracle and many more.
First open the ODBC Data Source 32Bit from the Control Panel. Switch to System DSN.
System DSN lists the System Data Sources. This list shows all system DSNs, including
thename of each DSN and the driver associated with the DSN. Click the Add button to
createnew Data Source See figure (4.1)

Select Oracle ODBC Driver or any other and click the Finish button to finish. This
will popup with a new window Oracle8 ODBC Driver Setup. Give the Data Source name as
oraodbc,UserID Scott and click OK to finish. (See figure 4.2)

8
Advance Java Programming (17625)

After finishing Oracle8 ODBC Driver set up, the ODBC Data Source Administrator
will bedisplaying the following. (See figure 4.3). Now the ODBC Driver Connection has
beenestablished. To display the driver-specific data source setup dialog box for a user
datasource, double-click the system DSN.Now the dialog box will be look as figure 4.3. Click
OK buttons to Complete the Connection.

JDBC Connection:
Sun offers a package java.sql that allows java program to access relational
databasemanagement systems (RDBMS). Through the JDBC a relational database can be
accessed using the sql. To communicate with a relational database the following steps have to
befollowed.Establish a connection between the Java program and the database manager. Send
a sql statement to the database by using a statement object. Read the results back from the
database and use them in the program.

Working with the driver manager:


JDBC is designed to work with many different database managers from
differentapplications. In order to establish a connection with a database the Java runtime
environmentmust load the driver for the specified database. The driver manager class is
responsible forloading and unloading drivers.

9
Advance Java Programming (17625)

Loading drivers:
JDBC drivers are typically written by a database vendor; they accept JDBC
connections andstatements from one side and issue native calls to the database from the other.
To use a JDBCdriver (including the JDBC-ODBC bridge driver) first thing is to loading it.
Preloading from Command line:
The command for the command line is
Java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver orajdbc
Preloading from program
The command line command will not be of much use for programs and applications;
asample programmatic version is given below. Usually the following statements will form
thefirst block in the JDBC programming.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.err.println("Unable to find JDBC driver");
}

4.4 JDBC Implementation:


JDBC is implemented as the java.sql package. This package contains all of the JDBC
classesand methods, as shown in Table 4.1.

Using the connection class:


10
Advance Java Programming (17625)

Once a driver has registered with the DriverManager connection to a database is made
simple. To invoke the driver and return a reference to a connection a new connection to
bemade.First specify the location of the database, then the user name and password.
Thesample code for connection isConnection myConnection = DriverManager.getConnection
(“jdbc:odbc:MyDataSource”, “Administrator”,
“Password”);
When DriverManager gets a getconnection() request, it takes the JDBC URL and
passes it toeach registered Driver in turn. The first Driver to recognize the URL and say that
it canconnect gets to establish the connection. If no Driver can handle the URL,
DriverManagerthrows a SQLException, reporting “no suitable driver”. To check whether
Driver has beeninstalled correctly, check for throwsexception errorUse the connection object
to connect to databases. By default, the new connection is set toauto-commit every statement
is instantly committed to the database.

DBC URL:
True to the nature of the Internet, JDBC identifies a database with an URL. The URL
is of theform:
jdbc:<subprotocol>:<subname related to the DBMS/Protocol>
For databases on the Internet or intranet, the subname can contain the Net URL
//hostname:port/ The <subprotocol> can be any name that a database understands. The odbc
subprotocol name is reserved for ODBC style data sources. A normal ODBC database JDBC
URL looks like the following:
jdbc:odbc:<ODBC DSN>;User=<username>;PW=<password>
To develop a JDBC driver with a new subprotocol, it is better to reserve the subprotocol
name
with JavaSoft, which maintains an informal subprotocol registry.

DriverPropertyInfo[] GetPropertyInfo (String url, java.util.Properties info)

11
Advance Java Programming (17625)

Int GetMajorVersion ()
Int getMinorVersion ()
Boolean jdbcCompliant ()
java.sql.DriverManager:-
Connection getConnection (String url, java.util.Properties info)
Connection getConnection (String url, String user, String password)
Connection getConnection (String url)
Driver getDriver (String url)
void registerDriver (java.sql.Driver driver)
void deregisterDriver (Driver driver)
java.util.Enumeration getDrivers ()
void setLoginTimeout (int seconds)
int getLoginTimeout ()
void setLogStream (java.io.PrintStream out)
java.io.PrintStream getLogStream ()
Void println (String message)
Class Initialization:
Routine:
Void Initialize ()
The Connection class is one of the major classes in JDBC. It packs a lot of
functionality,ranging from transaction processing to creating statements, in one class as seen
in Table 4.3.
Return Type Method Name Parameter
Statement-RelatedMethods
Statement createStatement ()
PreparedStatement prepareStatement (String sql)
CallableStatement prepareCall (String sql)
String nativeSQL (String sql)void close ()
Boolean isClosed ()

Metadata-RelatedMethods
DatabaseMetaData getMetaData ()
void SetReadOnly (boolean readOnly)

12
Advance Java Programming (17625)

Boolean IsReadOnly ()
void setCatalog (String catalog)
String getCatalog ()
SQLWarning getWarnings ()
void clearWarnings ()
Transaction-RelatedMethods
void setAutoCommit (booleanautoCommit)
Boolean getAutoCommit ()
void commit ()
void rollback ()
void SetTransactionIsolation (int level)
Int GetTransactionIsolation ()
java.sql.Connection Methods and Constants

Managing SQL transactions:


Use connection’s set auto commit () method to disable auto commit.Issue sql
statements
To commit the changes to the database, call commit () the transactions. To abandon all
thestatements made since last commit (), call rollback ().
Using the Statement:
Use a Statement object to hold sql statements. When a statement object is send to
thedatabase, the database runs the sql and returns a ResultSet.
Resultset myset = mystatement.executeQuery(“SELECT * FROM
CUSTOMERS”);
Or by
Resultset myset;
if(mystatement.execute(“SELECT * FROM CUSTOMERS”))
myset = mystatement.getResultset();
The execute () method returns a Boolean true if the Statement returned a ResultSet
and false ifit returned an integer. The execute () method is included in JDBC 2.0 and we will
be usingexecutequery () and executeupdate () and will be discussed later.

Statement:

13
Advance Java Programming (17625)

A Statement object is created using the createStatement() method in the Connection


object.Table 4.4 shows all methods available for the Statement object.

Return Type Method Name Parameter:


ResultSet executeQuery (String sql)
int executeUpdate (String sql)
boolean execute (String sql)
boolean getMoreResults ()
void close ()
int getMaxFieldSize ()
void setMaxFieldSize (int max)
int getMaxRows ()
void setMaxRows (int max)
void setEscapeProcessing (boolean enable)
int getQueryTimeout ()
void setQueryTimeout (int seconds)
void cancel ()
sql.SQLWarning getWarnings ()
void clearWarnings ()
void setCursorName (String name)
ResultSet getResultSet ()
Int getUpdateCount ()
Statement Object Methods
The most important methods are executeQuery (), executeUpdate () and execute().
Whencreating a Statement object with a SQL statement, the executeQuery () method takes a
SQLstring. It passes the SQL string to the underlying data source through the driver manager
andgets the ResultSet back to the application program. The executeQuery () method returns
onlyone ResultSet. For those cases that return more than one ResultSet, the execute ()
methodshould be used.
Complete Program:
Now we shall look at some complete programs. sql stament to to create a table
namedcustomers.
CREATE TABLE CUSTOMERS

14
Advance Java Programming (17625)

(
CUST_NUM INTEGER,
COMPANY VARCHAR(20),
CUST_REP INTEGER,
CREDIT_LIMIT NUMBER(7,2)
)
The following Java Program can create the same table Customers
import java.sql.*;
import java.io.*;
class Create
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();
stmt.executeUpdate("create table
customers(CUST_NUM int, COMPANY
char(20), CUST_REP int, CREDIT_LIMIT number(7,2))");
stmt.close();
con.close();
System.out.println("Table Successfully created");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
The output of the program isTable successfully created

15
Advance Java Programming (17625)

First statement import java.sql.* ; imports all classes that belong to the package sql.
All theJDBC code will be delimited in the try block to avoid any exceptional handling.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Specifies the type of driver to the JRT as JdbcOdbcDriver
Class.forName("my.sql.Driver");
When the method getConnection is called, the DriverManager will attempt to locate a
suitable driver from amongst those loaded at initialization and those loaded explicitly using
the same classloader as the current applet or application.
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");

Centre for Information Technology and Engineering, Manonaniam Sundaranar University


53
Creates Connection object named con.
A Connection's database is able to provide information describing its tables, its supported
SQL grammar, its stored procedures, the capabilities of this connection, and so on. This
information is obtained with the getMetaData method.

DriverManager:
As part of its initialization, the DriverManager class will attempt to load the driver
classesreferenced in the "jdbc.drivers" system property. This allows a user to customize the
JDBC
Drivers used by their applications.

Get connection:
Attempts to establish a connection to the given database URL. The DriverManager
attemptsto select an appropriate driver from the set of registered JDBC drivers.

Parameters:
url - a database url of the form jdbc:subprotocol:subname
info - a list of arbitrary string tag/value pairs as connection arguments; normally at least a
"user" and "password" property should be included
Returns:a Connection to the URL
Statement stmt = con.createStatement();

16
Advance Java Programming (17625)

The object used for executing a static SQL statement and obtaining the results
produced by it.Only one ResultSet per Statement can be open at any point in time. Therefore,
if the readingof one ResultSet is interleaved with the reading of another, each must have been
generated bydifferent Statements. All statement executes methods implicitly close a
statment's currentResultSet if an open one exists.

Create Statement:
Creates a Statement object for sending SQL statements to the database. SQL
statementswithout parameters are normally executed using Statement objects. If the same
SQLstatement is executed many times, it is more efficient to use a PreparedStatement JDBC
2.0
Result sets created using the returned Statement will have forward-only type, and
read-onlyconcurrency, by default.Returns: a new Statement object
Execute Update:
Executes an SQL INSERT, UPDATE or DELETE statement. In addition, SQL statements
thatreturn nothing, such as SQL DDL statements, can be executed.
Parameters:sql - a SQL INSERT, UPDATE or DELETE statement or a SQL statement that
returns nothing
Returns:either the row count for INSERT, UPDATE or DELETE or 0 for SQL statements
that returnnothingstmt.close();Releases this Statement object's database and JDBC resources
immediately instead of waitingfor this to happen when it is automatically closed.con.close();
Releases a Connection's database and JDBC resources immediately instead of waiting
forthem to be automatically releasedEvery object in sql package throws an exception. It is
handled by the try catch( e Exception)block.An exception that provides information on a
database access error, Each SQLException provides several kinds of information:a string
describing the error. This is used as the Java Exception message, available via themethod
getMessage ().a "SQLstate" string, which follows the XOPEN SQLstate conventions. The
values of theSQLState string are described in the XOPEN SQL spec.an integer error code
that is specific to each vendor. Normally this will be the actual errorcode returned by the
underlying database.a chain to a next Exception. This can be used to provide additional error
information.e.printStackTrace();Prints a message to the current JDBC log stream.

Selecting Rows:

17
Advance Java Programming (17625)

Selecting Rows from Customers table has the following sql code.
SELECT * FROM CUSTOMERS
Gives the following result. And the equivalent java code is given below.
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
101 NY TRADERS 5009 40000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000
import java.sql.*;
import java.io.*;
class SelectRow
{
public static void main(String[] args)
{
ResultSet rs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from
CUSTOMERS");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
System.out.println(rs.getInt("CUST_NUM") + "\t\t" +
rs.getString("COMPANY")+ "\t"+ rs.getInt("CUST_REP") + "\t" +
rs.getInt("CREDIT_LIMIT"));
}
stmt.close();
con.close();
System.out.println("Records successfully selected");

18
Advance Java Programming (17625)

}catch(Exception e)
{
e.printStackTrace();
}
}
}
The output of the program is
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
101 NY TRADERS 5009 40000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000
Records successfully selected

Resultset Processing: Retrieving Results:


Here we are using a new object ResultSet. A ResultSet provides access to a table of
data. AResultSet object is usually generated by executing a Statement. The ResultSet object
isactually a tabular data set; that is, it consists of rows of data organized in uniform columns.
Table 4.5 shows the methods associated with the ResultSet object.In JDBC, the Java program
can see only one row of data at one time. The program uses thenext() method to go to the
next row. JDBC does not provide any methods to move backwardsalong the ResultSet or to
remember the row positions (called bookmarks in ODBC). A ResultSetmaintains a cursor
pointing to its current row of data. Initially the cursor is positioned beforethe first row. The
'next' method moves the cursor to the next row. So in this program we areusing
while(rs.next()). The method rs.next() returns a boolean value depending on therecordset. If it
reaches last record false in returned and loop lapses.For maximum portability, ResultSet
columns within each row should be read in left-to-rightorder and each column should be read
only once.The JDBC driver attempts to convert the underlying data to the specified Java type
andreturns a suitable Java value through the getXXX methods. See the JDBC specification
forallowable mappings from SQL types to Java types with the ResultSet.getXXX methods.
Column names used as input to getXXX methods are case insensitive. When
performing agetXXX using a column name, if several columns have the same name, then the
value of thefirst matching column will be returned. The column name option is designed to be
used whencolumn names are used in the SQL query. For columns that are NOT explicitly

19
Advance Java Programming (17625)

named in thequery, it is best to use column numbers. If column names are used, there is no
way for theprogrammer to guarantee that they actually refer to the intended columns.A
ResultSet is automatically closed by the Statement that generated it when that Statement
isclosed, re-executed, or used to retrieve the next result from a sequence of multiple results.

Return Type Method Name Parameter:


Boolean next ()
void close ()
Boolean wasNull ()

Get Data By Column Position:


java.io.InputStream getAsciiStream (int columnIndex)
java.io.InputStream getBinaryStream (int columnIndex)
boolean getBoolean (int columnIndex)
byte getByte (int columnIndex)
byte[] getBytes (int columnIndex)
java.sql.Date getDate (int columnIndex)
double getDouble (int columnIndex)
float getFloat (int columnIndex)
int getInt (int columnIndex)
long getLong (int columnIndex)
java.lang.Bignum getBignum (int columnIndex, int
scale)
Object getObject (int columnIndex)
short getShort (int columnIndex)
String getString (int columnIndex)
java.sql.Time getTime (int columnIndex)
java.sql.Timestamp getTimestamp (int columnIndex)
java.io.InputStream getUnicodeStream (int columnIndex)

Get Data By ColumnName:


Java.io.InputStream getAsciiStream (String columnName)
Java.io.InputStream getBinaryStream (String columnName)
Boolean getBoolean (String columnName)
20
Advance Java Programming (17625)

Byte getByte (String columnName)


Byte[] getBytes (String columnName)
java.sql.Date getDate (String columnName)
double getDouble (String columnName)
float getFloat (String columnName)
int getInt (String columnName)
long getLong (String columnName)
java.lang.Bignum getBignum (String columnName,
int scale)
Object getObject (String columnName)
short getShort (String columnName)
String getString (String columnName)
java.sql.Time getTime (String columnName)
java.sql.Timestamp getTimestamp (String columnName)
java.io.InputStream getUnicodeStream (String columnName)
int findColumn (String columnName)
SQLWarning getWarnings ()
void clearWarnings ()
String getCursorName ()
ResultSetMetaData getMetaData ()

Table 4.5 java.sql.ResultSet Methods


The ResultSet methods even though there are many are very simple. The major ones
are thegetXXX() methods. The getMetaData() method returns the meta data information
about aResultSet. The DatabaseMetaData also returns the results in the ResultSet form. The
ResultSetalso has methods for the silent SQLWarnings. It is a good practice to check any
warningsusing the getWarning() method that returns a null if there are no warnings.Once the
program has a row, it can use the positional index (1 for the first column, 2 for thesecond
column, and so on) or the column name to get the field value by using the
getXXXX()methods.
The getXXX methods retrieve column values for the current row. Retrieve values
usingeither the index number of the column or the name of the column. In general, using

21
Advance Java Programming (17625)

thecolumn index will be more efficient. Columns are numbered from 1.Here is the revised
version of Selecting Row using the column number
import java.sql.*;
import java.io.*;
class SelectRow
{
public static void main(String[] args)
{

ResultSet rs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from CUSTOMERS");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no+"\t\t"+company+"\t"+rep+"\t\t"+credit);
}
stmt.close();
con.close();
System.out.println("Records successfully selected");
}catch(Exception e)
{
e.printStackTrace();

22
Advance Java Programming (17625)

}
}
}

Deleting a Record:
In thin proogram records are being deleted from the customers. Here we are using both the
executeUpdate() and executeQuery() to deleting and retriving records from the Customers
table. The executeUpdate() returns void and executeQuery() returns a ResultSet object. Here
is the complete program.
//PROGRAM TO DELETE A RECORD
import java.sql.*;
import java.io.*;
class Deleterecord
{
public static void main(String[] args)
{
ResultSet rs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();
stmt.executeUpdate
("delete from CUSTOMERS where CUST_NUM = 101");
rs = stmt.executeQuery("select * from customers");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);

23
Advance Java Programming (17625)

double credit=rs.getDouble(4);
System.out.println( no + "\t\t"+company + "\t" + rep + "\t\t" + credit);
}
stmt.close();
con.close();
System.out.println("Record Successfully deleted");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
The result of the program
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
102 RAVI AND CO 5008 50000.0
103 RAM BROTHERS 5007 23000.0

Record successfully deletedInserting values in to the database. This program is very similar
to the delete recordsprogram.
Inserting a Record:
//PROGRAM FOR INSERTING A RECORD
import java.sql.*;
import java.io.*;
class Insert
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();

24
Advance Java Programming (17625)

stmt.executeUpdate("insert into CUSTOMERS values


(1,'CHARLIE AND CO',20,45000)");
stmt.executeUpdate("insert into CUSTOMERS values
(2,'ARVIND MILLS',30,50000)");
stmt.executeUpdate("insert into CUSTOMERS values
(3,'PANDY BROTHERS',20,12500)");
ResultSet rs = stmt.executeQuery("select * from CUSTOMERS");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println( no + "\t\t"+company + "\t" + rep + "\t\t" +
credit);
}
stmt.close();
con.close();
System.out.println("Records successfully
inserted");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
The output of the program
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
2 ARVIND MILLS 30 50000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000

25
Advance Java Programming (17625)

1 CHARLIE AND CO 20 45000


3 PANDY BROTHERS 20 12500
Records successfully inserted

Updating Records:
This program updates records in the customer table. Here the credit_limit of the Arvind
Mills(whose CUST_NUM is 2) has been updated from 50,000 to 2,00,000
//PROGRAM FOR UPDATING A RECORD
import java.sql.*;
import java.io.*;
class UpdateCust
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();
stmt.executeUpdate("update CUSTOMERS set
CREDIT_LIMIT = 200000 where CUST_NUM =2");
ResultSet rs = stmt.executeQuery("select * from
CUSTOMERS");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no + "\t\t"+company + "\t" + rep + "\t\t" +

26
Advance Java Programming (17625)

credit);
}
stmt.close();
con.close();
System.out.println("Records successfully updated");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
2 ARVIND MILLS 30 200000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000
1 CHARLIE AND CO 20 45000
3 PANDY BROTHERS 20 12500
Records successfully updated

Deleting a Table:
//PROGRAM TO DROP A TABLE
import java.sql.*;
import java.io.*;
class Drop
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement();

27
Advance Java Programming (17625)

stmt.executeUpdate("drop table CUSTOMERS");


ResultSet rs = stmt.executeQuery("select * from
tab");
System.out.println("TNAME" + "\t\tTABTYPE" +
"\tCLUSTERID");
while(rs.next())
{
String name = rs.getString(1);
String type = rs.getString(2);
String clus = rs.getString(3);
System.out.println( name + "\t\t" + type + "\t" + clus);
}
stmt.close();
con.close();
System.out.println("Customer Table successfully dropped");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
The output of the program would be similar to this.

TNAME TABTYPE CLUSTERID


BONUS TABLE null
DEPT TABLE null
EMP TABLE null
EMP1 TABLE null
SALGRADE TABLE null
SAL_DET TABLE null
Customer Table successfully dropped

28
Advance Java Programming (17625)

Prepared Statement:
In the case of a PreparedStatement object, as the name implies, the application
programprepares a SQL statement using the
java.sql.Connection.PrepareStatement()method.ThePreparedStatement() method takes a SQL
string, which is passed to the underlying DBMS.
The DBMS goes through the syntax run, query plan optimization, and the execution
plangeneration stages, but does not execute the SQL statement. Possibly, it returns a handle
to theoptimized execution plan that the JDBC driver stores internally in the
PreparedStatementobject.The methods of the PreparedStatement object are shown in Table
4.6 Notice that the
executeQuery(), executeUpdate(), and execute() methods do not take any parameters.
Theyare just calls to the underlying DBMS to perform the already-optimized SQL statement.

Return Type Method Name Parameter:


ResultSet executeQuery ()
Int executeUpdate ()
Boolean execute ()
Table 4.6 Prepared Statement Object Methods
One of the major features of a PreparedStatement is that it can handle IN types of parameters.
The parameters are indicated in a SQL statement by placing the "?" as the parameter
markerinstead of the actual values. In the Java program, the association is made to the
parameters
with the setXXXX() methods, as shown in Table 4.7 All of the setXXXX() methods take
theparameter index, which is 1 for the first "?," 2 for the second "?," and so on.

Return Type Method Name Parameter:


void ClearParameters ()
void SetAsciiStream (int parameterIndex, java.io.InputStream x, int length)
void SetBinaryStream (int parameterIndex, java.io.InputStream x, int length)
void SetBoolean (int parameterIndex, boolean x)
void setByte (int parameterIndex, byte x)
void 1setBytes (int parameterIndex, byte x[])
void setDate (int parameterIndex, java.sql.Date x)

29
Advance Java Programming (17625)

void setDouble (int parameterIndex, double x)


void setFloat (int parameterIndex, float x)
void setInt (int parameterIndex, int x)
void setLong (int parameterIndex, long x)
void setNull (int parameterIndex, int sqlType)
void SetBignum (int parameterIndex, Bignum x)
void setShort (int parameterIndex, short x)
void setString (int parameterIndex, String x)
void setTime (int parameterIndex, java.sql.Time x)
void SetTimestamp (int parameterIndex, java.sql.Timestamp x)
void SetUnicodeStream (int parameterIndex, java.io.InputStream x, int length)

Advanced Features— Object Manipulation


Void setObject (int parameterIndex, Object x, int targetSqlType, int
scale)
Void setObject (int parameterIndex, Object x, int targetSqlType)
Void setObject (int parameterIndex, Object x)

Table 4.7 java.sql.PreparedStatement--Parameter-Related Methods


In the case of the PreparedStatement, the driver actually sends only the execution plan
ID andthe parameters to the DBMS. This results in less network traffic and is well-suited for
Javaapplications on the Internet. The PreparedStatement should be used when needed to
executethe SQL statement many times in a Java application. But remember, even though
theoptimized execution plan is available during the execution of a Java program, the
DBMSdiscards the execution plan at the end of the program. So, the DBMS must go through
all ofthe steps of creating an execution plan every time the program runs. The
PreparedStatementobject achieves faster SQL execution performance than the simple
Statement object, as the DBMS does not have to run through the steps of creating the
execution plan.
The following example program shows how to use the PreparedStatement class to
access adatabase. The simple Statement example can be improved in a few major ways. First,
theDBMS goes through building the execution plan every time, so make it a
PreparedStatement.Secondly, the query lists all courses, which could scroll away.

30
Advance Java Programming (17625)

//PROGRAM FOR PREPARE STATEMENT


import java.sql.*;
import java.io.*;
class PrepareSt
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
PreparedStatement ps = con.prepareStatement("Select * from CUSTOMERS
where CREDIT_LIMIT >= ?");
ps.setInt(1,50000);
ResultSet rs=ps.executeQuery();
// ResultSet rs = stmt.executeQuery("select * from
CUSTOMERS");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no+"\t\t"+company+"\t"+rep+"\t\t"
+credit);
}
rs.close();
ps.close();
con.close();
}catch(Exception e)

31
Advance Java Programming (17625)

{
e.printStackTrace();
}
}
}
The output of the program may be equal to
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
2 ARVIND MILLS 30 900000.0

5.3 Callable Statement:


For a secure, consistent, and manageable multi-tier client/server system, the data
accessshould allow the use of stored procedures. Stored procedures centralize the business
logic interms of manageability and also in terms of running the query. JDBC allows the use
of storedprocedures by the CallableStatement class and with the escape clause string.
A CallableStatement object is created by the prepareCall() method in the Connection
object.The prepareCall() method takes a string as the parameter. This string, called an escape
clause,is of the form
{[? =] call <stored procedure name>
[<parameter>,<parameter> ...]}
The CallableStatement class supports parameters. These parameters are of the OUT
kind froma stored procedure or the IN kind to pass values into a stored procedure. The
parametermarker (question mark) must be used for the return value (if any) and any output
argumentsbecause the parameter marker is bound to a program variable in the stored
procedure. Inputarguments can be either literals or parameters. For a dynamic parameterized
statement, theescape clause string takes the form.
{[? =] call <stored procedure name> [<?>,<?> ...]}
The OUT parameters should be registered using the registerOutparameter() method asshown
in Table 4.8 before the call to the executeQuery(), executeUpdate(), or execute()methods.

Return Type Method Name Parameter:


Void RegisterOutParameter (int parameterIndex, int
sqlType)
Void RegisterOutParameter (int parameterIndex, int
sqlType, int scale)
32
Advance Java Programming (17625)

Table 4.8 CallableStatement--OUT Parameter Register Methods


After the stored procedure is executed, the DBMS returns the result value to the JDBC driver.
This return value is accessed by the Java program using the methods in Table 4.9

Return Type Method Name Parameter:


Boolean getBoolean (int parameterIndex)
Byte getByte (int parameterIndex)
byte[] getBytes (int parameterIndex)
java.sql.Date getDate (int parameterIndex)
double getDouble (int parameterIndex)
float getFloat (int parameterIndex)
int getInt (int parameterIndex)
long getLong (int parameterIndex)
java.lang.Bignum getBignum (int parameterIndex,
int scale)
Object getObject (int parameterIndex)
short getShort (int parameterIndex)
String getString (int parameterIndex)
java.sql.Time getTime (int parameterIndex)
java.sql.Timestamp getTimestamp (int parameterIndex)

Miscellaneous Functions:
boolean wasNull ()

Table 4.9 CallableStatement Parameter Access Methods


Consider a table of emp1 with the following structure.
EMPNO NAME AGE SAL DEPTNO
101 aaa 24 9400 10
102 bbb 25 12400 20
103 ccc 27 11400 30

Creating a procedure:
33
Advance Java Programming (17625)

The code given below crates a procedure named proc, which increases the credit limit by
n.create or replace procedure proc(n number)
as
begin
update customers set CREDIT_LIMIT = CREDIT_LIMIT + n;
commit;
end;
//Program for procedure
import java.sql.*;
import java.io.*;
public class Procedure
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");
System.out.print("Enter Credit limit increment:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str=br.readLine();
int p=Integer.parseInt(str);
CallableStatement cs=con.prepareCall("{ call proc(?)
}");
cs.setInt(1,100);
cs.execute();
System.out.println("Procedure Executed");
cs.close();
Statement st = con.createStatement();
ResultSet rs=st.executeQuery("Select * from
Customers");

34
Advance Java Programming (17625)

while(rs.next())
{
int eno=rs.getInt(1);
String name=rs.getString(2);
int ag=rs.getInt(3);
double sal=rs.getDouble(4);
System.out.println(eno+"\t"+name+"\t"+ag+"\t"+sal);
}
rs.close();
st.close();
con.close();
}
catch(SQLException es)
{
System.out.println(es);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
The output of the program will be similar to
Enter Credit limit increment: 1000
Procedure Executed
1 CHARLIE AND CO 20 47200.0
2 ARVIND MILLS 30 902200.0
3 PANDY BROTHERS 20 14700.0

5.4 Other JDBC Classes:


Now those have seen all of the main database-related classes, look at some of the supporting
classes that are available in JDBC. These classes include the Date, Time, TimeStamp, and so
on. Most of these classes extend the basic Java classes to add capability to handle and

35
Advance Java Programming (17625)

translate data types that are specific to SQL.

java.sql.Date
This package (see Table 4.10) gives a Java program the capability to handle SQL DATE
information with only year, month, and day values.

Return Type Method Name Parameter:


Date Date (int year, int month, int day)
Date Date (long date)
Date valueOf (String s)
String toString ()
int getHours ()
int getMinutes ()
int getSeconds ()
void setHours (int Hr)
void setMinutes (int Min)
void setSeconds (int Sec)
void setTime (long date)
Table 4.10 java.sql.Date Methods:-
java.sql.Time
As seen in Table 4.11, the java.sql.Time adds the Time object to the java.util.Date package to
handle only hours, minutes, and seconds. java.sql.Time is also used to represent SQL TIME
information.

Return Type Method Name Parameter:


Time Time (int hour, int minute, int
second)
Time Time (long time)
Time Time valueOf(String s)
String toString ()
Int getDate ()
int getDay ()
int getMonth ()

36
Advance Java Programming (17625)

int getYear ()
void setDate (int date)
void setMonth (int month)
void setTime (int time)
void SetYear (int year)

Table 4.11 java.sql.Time Methods:-


java.sql.Timestamp
The java.sql.Timestamp package adds the TimeStamp class to the java.util.Date package (see
Table 4.12). It adds the capability of handling nanoseconds. But the granularity of the
subsecond timestamp depends on the database field as well as the operating system.

Return Type Method Name Parameter:


TimeStamp TimeStamp (int year, int month, int date, int
hour, int minute, int second, int nano)
TimeStamp TimeStamp (long time)
TimeStamp valueOf (String s)
String toString ()
int getNanos ()
void setNanos (int n)
boolean after (TimeStamp ts)
boolean before (TimeStamp ts)
boolean equals (TimeStamp ts)

Table 4.12 java.sql.Timestamp Methods:-


java.sql.Types
This class defines a set of XOPEN equivalent integer constants that identify SQL types. The
constants are final types. Therefore, they cannot be redefined in applications or applets. Table
4.13 lists the constant names and their values.
Constant Name Value:
BIGINT -5
BINARY -2
BIT -7
CHAR 1
DATE 91
37
Advance Java Programming (17625)

DECIMAL 3
DOUBLE 8
FLOAT 6
INTEGER 4
LONGVARBINARY -4
LONGVARCHAR -1
NULL 0
NUMERIC 2
OTHER 1111
REAL 7
SMALLINT 5
TIME 92
TIMESTAMP 93
TINYINT -6
VARBINARY -3
VARCHAR 12
Table 4.13 java.sql.Types Constants:-

Moving the Cursor in Scrollable Result Sets:


One of the new features in the JDBC 2.0 API is the ability to move a result set's
cursorbackward as well as forward. There are also methods that are used to move the cursor
to aparticular row and check the position of the cursor. Scrollable result sets make it possible
tocreate a GUI (graphical user interface) tool for browsing result sets, which will probably
beone of the main uses for this feature. Another use is moving to a row in order to update it.
Before taking advantage of these features, it is easy to create a scrollable ResultSet
object. Thefollowing line of code illustrates one way to create a scrollable ResultSet object:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT * FROM CUSTOMERS ");
This code is similar to the earlier ResultSet object, except that it adds two arguments to
themethod createStatement. The first argument is one of three constants added to the
ResultSet
API to indicate the type of a ResultSet object:

38
Advance Java Programming (17625)

TYPE_FORWARD_ONLY ,
TYPE_SCROLL_INSENSITIVE , and
TYPE_SCROLL_SENSITIVE .
The second argument is one of two ResultSet constants for specifying whether a result
set isread-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The
point toremember here is that if a type is specified, it must also be specified whether it is
read-only orupdatable. Also, first of all the type must be specified, because both parameters
are of type int, the compiler will not complain if the order is switched.
Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set,
that is,one in which the cursor moves only forward. If the type is not specified the default is
TYPE_FORWARD_ONLY and CONCUR_READ_ONLY (as is the case of using only the
JDBC 1.0 API).
Scrollable ResultSet object can be got only by specifying the following ResultSet
constants:TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE.
The difference between the two has to do with whether a result set reflects changes that
aremade to it while it is open and whether certain methods can be called to detect these
changes.
Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect
changesmade while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All
three types ofresult sets will make changes visible if they are closed and then reopened. At
this stage, notneed to worry about the finer points of a ResultSet object's capabilities. No
matter what typeof result set to specify, limitation is that DBMS and driver actually provide.
A scrollable ResultSet object can be used to move the cursor around in the result set.
Remember that when a new ResultSet object is created, it had a cursor positioned before
thefirst row. Even when a result set is scrollable, the cursor is initially positioned before the
firstrow. In the JDBC 1.0 API, the only way to move the cursor was to call the method next.
Thisis still the appropriate method to call when it is absolutely necessary to access each row
once,going from the first row to the last row, but there are so many other ways to move the
cursor.
The counterpart to the method next, which moves the cursor forward one row (toward theend
of the result set), is the new method previous, which moves the cursor backward (onerow
toward the beginning of the result set). Both methods return false when the cursor
goesbeyond the result set (to the position after the last row or before the first row), which

39
Advance Java Programming (17625)

makes itpossible to use them in a while loop. The next method has been already used in the
whileloop.have already used the method next in a while loop, but to refresh the memory, here
is anexample in which the cursor moves to the first row and then to the next row each time it
goesthrough the while loop. The loop ends when the cursor has gone after the last row,
causingthe method next to return false. The following code fragment prints out the values in
eachrow of srs, with five spaces between the name and price:Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(
"SELECT * FROM CUSTOMERS");
while (srs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no+"\t\t"+company+"\t"+rep+"\t\t"+credit);
}
The printout will look something like this:
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 CHARLIE AND CO 20 47200
2 ARVIND MILLS 30 902200
3 PANDY BROTHERS 20 14700
All of the rows is ResultSet going backward, but to do this, the cursor must start out
beingafter the last row. Move the cursor explicitly to the position after the last row with the
method aftertaste. Then the method previous moves the cursor from the position after thelast
row to the last row, and then to the previous row with each iteration through the whileloop.
The loop ends when the cursor reaches the position before the first row, where themethod
previous returns false.Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT * FROM CUSTOMERS");
srs.afterLast();

40
Advance Java Programming (17625)

while (srs.previous()) {
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no+"\t\t"+company+"\t"+rep+"\t\t"+credit);
}
The printout will look similar to this:
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 PANDY BROTHERS 20 14700
2 ARVIND MILLS 30 902200
3 CHARLIE AND CO 20 47200
Moving the cursor to a particular row in a ResultSet object. The methods first, last,
beforeFirst, and afterLast move the cursor to the row indicated in their names. The method
absolute will move the cursor to the row number indicated in the argument passed to it. If
the number is positive, the cursor moves the given number from the beginning, so calling
absolute(1) puts the cursor on the first row. If the number is negative, the cursor moves the
given number from the end, so calling absolute(-1) puts the cursor on the last row. The
following line of code moves the cursor to the fourth row of srs :
srs.absolute(2);
If srs has 500 rows, the following line of code will move the cursor to row 497:
srs.absolute(-4);
Three methods move the cursor to a position relative to its current position. The
method nextmoves the cursor forward one row, and the method previous moves the cursor
backward onerow. With the method relative how many rows to move from the current row
and also thedirection in which to move can be specified. A positive number moves the cursor
forward thegiven number of rows; a negative number moves the cursor backward the given
number ofrows. For example, in the following code fragment, the cursor moves to the fourth
row, then
to the first row, and finally to the third row:
srs.absolute(4); // cursor is on the fourth row
...
srs.relative(-3); // cursor is on the first row

41
Advance Java Programming (17625)

...
srs.relative(2); // cursor is on the third row
The method getRow lets check the number of the row where the cursor is positioned.
Forexample, use getRow to verify the current position of the cursor in the previous example
asfollows:
srs.absolute(4);
int rowNum = srs.getRow(); // rowNum should be 4
srs.relative(-3);
int rowNum = srs.getRow(); // rowNum should be 1
srs.relative(2);
int rowNum = srs.getRow(); // rowNum should be 3
Four additional methods verify whether the cursor is at a particular position. The position
isstated in their names: isFirst, isLast, isBeforeFirst, isAfterLast. These methods all return
aboolean and can therefore be used in a conditional statement. For example, the
followingcode fragment tests to see whether the cursor is after the last row before invoking
the methodprevious in a while loop. If the method isAfterLast returns false, the cursor is not
after the lastrow, so the method afterLast is invoked. This guarantees that the cursor will be
after the lastrow and that using the method previous in the while loop will cover every row in
srs .
if (srs.isAfterLast() == false) {
srs.afterLast();
}
while (srs.previous())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no+"\t\t"+company+"\t"+rep+"\t\t"+credit);
}
Making Updates to Updatable Result Sets:

42
Advance Java Programming (17625)

Another new feature in the JDBC 2.0 API is the ability to update rows in a result set
usingmethods in the Java programming language rather than having to send an SQL
command.
But before taking the advantage of this capability, create a ResultSet object that is updatable.
In order to do this, supply the ResultSet constant CONCUR_UPDATABLE to
thecreateStatement method. The Statement object it creates will produce an updatable
ResultSetobject each time it executes a query. The following code fragment illustrates
creating theupdatable ResultSet object uprs . Note that the code also makes uprs scrollable.
An updatable
ResultSet object does not necessarily have to be scrollable, but when making changes to
aresult set, generally want to be able to move around in it. A scrollable result set, can move
torows that need to be changed, and if the type is TYPE_SCROLL_SENSITIVE, it can get
thenew value in a row after the chang had made.
Connection con = DriverManager.getConnection("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT * FROM CUSTOMERS ");
The ResultSet object uprs might look something like this:
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 CHARLIE AND CO 20 47200
2 ARVIND MILLS 30 902200
3 PANDY BROTHERS 20 14700
We can now use the new JDBC 2.0 methods in the ResultSet interface to insert a new row
into
uprs , delete an existing row from uprs , or modify a column value in uprs .

Updating a Result Set Programmatically:


An update is the modification of a column value in the current row. Using the JDBC
1.0 API,the update would look something like this:stmt.executeUpdate("UPDATE
CUSTOMERS SET CREDIT_LIMIT = 90100" +
"WHERE CUST_REP = 20");
The following code fragment shows another way to accomplish the update, this time using
the JDBC 2.0 API:

43
Advance Java Programming (17625)

uprs.last();
uprs.updateFloat("CREDIT_LILMIT", 90100f);
Update operations in the JDBC 2.0 API affect column values in the row where the
cursor ispositioned, so in the first line the ResultSet uprs calls the method last to move its
cursor to thelast row (the row where the column CREDIT_LIMIT has the value 20). Once the
cursor is onthe last row, all of the update methods will operate on that row until the cursor is
moved toanother row. The second line changes the value in the CREDIT_LIMIT column to
90100 bycalling the method updateFloat. This method is used because the column value we
want toupdate is a float in the Java programming language.The Resultet. updateXXX
methods take two parameters: the column to update and the newvalue to put in that column.
As with the ResultSet. getXXX methods, the parameterdesignating the column may be either
the column name or the column number. There is adifferent updateXXX method for updating
each datatype (updateString , updateBigDecimal ,
updateInt , and so on) just as there are different getXXX methods for retrieving different
datatypes.
uprs.last();
uprs.updateFloat("CREDIT_LIMIT", 90100f);
uprs.updateRow();
If the cursor is moved to a different row before calling the method updateRow , the
updatewould have been lost. If, on the other hand, that the CREDIT_LIMIT should really
have notbeen changed for Charlie and co it is easy to cancel the update by calling the
methodcancelRowUpdates . To invoke cancelRowUpdates before invoking the method
updateRow ;once updateRow is called, calling the method cancelRowUpdates does nothing.
Note thatcancelRowUpdates cancels all of the updates in a row, so if there are many
invocations of theupdateXXX methods on the same row, just charlie and co cannot be
canceled. The followingcode fragment first cancels updating the CREDIT_LIMIT to 90100.
uprs.last();
uprs.updateFloat("CREDIT_LIMIT", 90100);
uprs.cancelRowUpdates();
In this example, only one column value was updated, but calling an appropriate
updateXXXmethod for any or all of the column values in a single row. The concept to
remember is thatupdates and related operations apply to the row where the cursor is

44
Advance Java Programming (17625)

positioned. Even if thereare many calls to updateXXX methods, it takes only one call to the
method updateRow toupdate the database with all of the changes made in the current row.

Inserting and Deleting Rows Programmatically:


In the previous section, we saw how to modify a column value using methods in the
JDBC 2.0API rather than having to use SQL commands. With the JDBC 2.0 API, see also
inserting anew row into a table or deleting an existing row programmatically.Let's suppose
that our coffee house proprietor is getting a new variety from one of his coffeesuppliers, The
High Ground, and wants to add the new coffee to his database. Using theJDBC 1.0 API, he
would write code that passes an SQL insert statement to the DBMS. Thefollowing code
fragment, in which stmt is a Statement object, shows this approach:
stmt.executeUpdate("INSERT INTO CUSTOMERS " +
"VALUES (4,'PRAKASH POLYMERS', 40, 35000)");
The same thing can be done without using any SQL commands by using ResultSet
methodsin the JDBC 2.0 API. Basically, after a ResultSet object with results from the
tableCUSTOMERS, can build the new row and then insert it into both the result set and the
tableCUSTOMERS in one step. Build a new row in what is called the insert row, a special
rowassociated with every ResultSet object. This row is not actually part of the result set.First
step will be to move the cursor to the insert row, which can be done by invoking themethod
moveToInsertRow . The next step is to set a value for each column in the row. Thiscan be
done by calling the appropriate updateXXX method for each value. Note that these arethe
same updateXXX methods used in the previous section for changing a column value.Finally,
call the method insertRow to insert the row that just populated with values into theresult set.
This one method simultaneously inserts the row into both the ResultSet object andthe
database table from which the result set was selected. The following code fragment creates
the scrollable and updatable ResultSet object uprs ,which contains all of the rows and
columns in the table COFFEES :
Connection con =
DriverManager.getConnection("jdbc:odbc:oraodbc","scott","tiger");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT * FROM

45
Advance Java Programming (17625)

Customers");
The next code fragment uses the ResultSet object uprs to insert the row for
PRAKASHPOLYMERS, shown in the SQL code example. It moves the cursor to the insert
row, sets thefive column values, and inserts the new row into uprs and CUSTOMERS :
uprs.moveToInsertRow();
uprs.updateInt("CUST_NUM", 4);
uprs.updateString("COMPANY", "PRAKASH POLYMERS");
uprs.updateInt("CUST_REP", 40);
uprs.updateFloat("CREDIT_LIMIT", 35000);
uprs.insertRow();
Because either the column name or the column number to indicate the column to be set, code
for setting the column values could also have looked like this:
uprs.updateInt(1, 4);
uprs.updateString(2, “PRAKASH POLYMERS”);
uprs.updateInt(3, 40);
uprs.updateFloat(4, 35000);
To insert a row do not supply a value for every column in the row. If a value for a
column isomitted that was defined to accept SQL NULL values, then the value assigned to
that columnis NULL. If a column does not accept null values, however, a SQLException
when anupdateXXX method is not called, to set a value for it. This is also true if a table
column ismissing in the ResultSet object.In the example above, the query was SELECT *
FROM CUSTOMERS, which produced aresult set with all the columns of all the rows. To
insert one or more rows, the query does nothave to select all rows, but it is safer to select all
columns. Especially if the table has hundredsor thousands of rows, use a WHERE clause to
limit the number of rows returned by the
SELECT statement.
After having called the method insertRow, just start building another row to be
inserted, ormove the cursor back to a result set row. For instance, invoke any of the methods
that put thecursor on a specific row, such as first, last , beforeFirst , afterLast , and absolute .
Also usethe methods previous, relative , and moveToCurrentRow . Note that
moveToCurrentRowcan only be invoked when the cursor is on the insert row.To call the
method moveToInsertRow , the result set records which row the cursor is sittingon, which is

46
Advance Java Programming (17625)

by definition the current row. As a consequence, the methodmoveToCurrentRow can move


the cursor from the insert row back to the row that waspreviously the current row.
Code Sample for Inserting a Row:
The following code sample is a complete program that should run if have a JDBC 2.0
Compliant driver that implements scrollable result sets. At the time of this writing there
arenot yet any JDBC 2.0 Compliant drivers, so this code, though it compiles, has not been
testedon a driver and DBMS.The ResultSet object uprs is updatable, scrollable, and sensitive
to changes made by itself andothers. Even though it is TYPE_SCROLL_SENSITIVE, it is
possible that the getXXX methodscalled after the insertions will not retrieve values for the
newly-inserted rows. There aremethods in the DatabaseMetaData interface that will tell
whatis visible and what is detected in the different types of result sets for the driver and
DBMS. These methods are discussed indetail in JDBC Database Access with Java, but they
are beyond the scope of this tutorial. Inthis code sample we wanted to demonstrate cursor
movement in the same ResultSet object, soafter moving to the insert row and inserting two
rows, the code moves the cursor back to theresult set, going to the position before the first
row. This puts the cursor in position to iteratethrough the entire result set using the method
next in a while loop. To be absolutely sure thatthe getXXX methods include the inserted row
values no matter what driver and DBMS isused, close the result set and create another one,
reusing the same Statement object stmt andagain using the query SELECT * FROM
CUSTOMERS.After all the values for a row have been set with updateXXX methods, the
code inserts therow into the result set and the database with the method insertRow. Then, still
staying on theinsert row, it sets the values for another row.
import java.sql.*;
import java.io.*;
class ScrollSelect
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:oraodbc","scott","tiger");

47
Advance Java Programming (17625)

Statement stmt = con.createStatement


(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM
CUSTOMERS");
rs.moveToInsertRow();
rs.updateInt("CUST_NO", 4);
rs.updateString("COMPANY_NAME", "PRAKASH POLYMERS");
rs.updateInt("CUST_REP", 40);
rs.updateFloat("CREDIT_LIMIT", 35000f);
rs.insertRow();
rs.updateInt("CUST_NO", 5);
rs.updateString("COMPANY_NAME", "BALAJI
BROTHERS");
rs.updateInt("CUST_REP", 50);
rs.updateFloat("CREDIT_LIMIT", 50000f);
rs.insertRow();
rs.beforeFirst();
System.out.println("Table CUSTOMERS after insertion:");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while (rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4);
System.out.println(no+"\t\t"+company+
"\t"+rep+"\t\t"+credit);
}
rs.close();
stmt.close();
con.close();

48
Advance Java Programming (17625)

System.out.println("Records succesfully selected");


}catch(Exception e)
{
e.printStackTrace();
}
}
}

Deleting a Row:
Deleting a row is the third way to modify a ResultSet object, and it is the simplest. To
do ismove the cursor to the row that need to be deleted and then call the method deleteRow .
Forexample, to delete the fourth row in the ResultSet uprs , the code will look like this:
uprs.absolute(4);
uprs.deleteRow();
The fourth row has been removed from uprs and also from the database.
The only issue about deletions is what the ResultSet object actually does when it
deletes arow. With some JDBC drivers, a deleted row is removed and is no longer visible in a
resultset. Some JDBC drivers use a blank row as a placeholder (a "hole") where the deleted
rowused to be. If there is a blank row in place of the deleted row, use the method absolute
withthe original row positions to move the cursor because the row numbers in the result set
arenot changed by the deletion.
In any case, remember that JDBC drivers handle deletions differently. For example, to
writean application meant to run with different databases, don’t write code that depends on
therebeing a hole in a result set.

Seeing Changes in Result Sets:


To modify data in a ResultSet object, the change will always be visible if the object is
closed,and then reopen it. In other words, if the same query is re-executed, it will produce a
newresult set, based on the data currently in a table. This result set will naturally reflect
changesanyone made earlier.With a ResultSet object that is TYPE_SCROLL_SENSITIVE,
seeing the updates anyone makesto column values. The only way to be sure is to use
49
Advance Java Programming (17625)

DatabaseMetaData methods that returnthis information.To some extent regulate what changes
are visible by raising or lowering the transactionisolation level for the connection with the
database. For example, the following line of code,where con is an active Connection object,
sets the connection's isolation level toTRANSACTION_READ_COMMITTED:
con.setTransactionIsolation(TRANSACTION_READ_COMMITTED);
With this isolation level, the ResultSet object will not show any changes before they
arecommitted, but it can show changes that may have other consistency problems. To
allowfewer data inconsistencies, raise the transaction isolation level to
TRANSACTION_REPEATABLE_READ. The problem is that the higher the isolation
level,the poorer the performance. And, as is always true of databases and drivers, the
limitation iswhat they actually provide. Many programmers just use their database's default
transactionisolation level.In a ResultSet object that is TYPE_SCROLL_INSENSITIVE,
generally cannot see changesmade to it while it is still open. Use only this type of ResultSet
object because they want aconsistent view of data and do not want to see changes made by
others.Use the method refreshRow to get the latest values for a row straight from the
database. Thismethod can be very expensive, especially if the DBMS returns multiple rows
each time callrefreshRow. Nevertheless, its use can be valuable if it is critical to have the
latest data. Evenwhen a result set is sensitive and changes are visible, an application may not
always see thevery latest changes that have been made to a row if the driver retrieves several
rows at a timeand caches them. Thus, using the method refreshRow is the only way to be sure
that you areseeing the most up-to-date data.
The following code sample illustrates how an application might use the method
refreshRowwhen it is absolutely critical to see the most current values. Note that the result set
should besensitive; that is the method refreshRow with a ResultSet object that is
TYPE_SCROLL_INSENSITIVE , refreshRow does nothing.
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("SELECT * from
customers ");
rs.absolute(4);
float AMOUNT1 = rs.getFloat("CDREDIT_LIMIT");
// do something. . .

50
Advance Java Programming (17625)

rs.absolute(4);
rs.refreshRow();
float AMOUNT2 = rs.getFloat("CREDIT_LIMIT");
if (AMOUNT1>AMOUNT2) {
// do something. . .

Multiple Choice Questions

1. Which of the following allows non repeatable read in JDBC Connection?


A. TRANSACTION_READ_UNCOMMITTED.
B. TRANSACTION_READ_COMMITTED.
C. TRANSACTION_SERIALIZABLE.
D. TRANSACTION_REPEATABLE_READ.
ANSWER: D
2. Which of the following statements is false as far as different type of statements is
concern in JDBC?
A. Prepared Statement.
B. Callable Statement.
C. Interim Statement.
D. Regular Statement.
ANSWER: C
3. Which of the following methods are needed for loading a database driver in JDBC?
A. registerDriver() method.
B. Class.forName().
C. Both A and B.
D. getConnection().
ANSWER: C
4. Which of the following is false as far as type 4 driver is concern?
51
Advance Java Programming (17625)

A. Type 4 driver is "native protocol, pure java" driver.


B. Type 4 drivers are 100% Java compatible.
C. Type 4 drivers can not be used with Netscape.
D. Type 4 driver cannot be used with Internet Explorer.
ANSWER: C
5. Which driver is efficient and always preferable for using JDBC applications?
A. Type - 4.
B. Type - 1.
C. Type - 3.
D. Type - 2.
ANSWER: A
6. The JDBC-ODBC Bridge is
A. Three tiered.
B. Multithreaded.
C. Best for any platform.
D. All of the above.
ANSWER: B
7. What is the disadvantage of Type-4 Native-Protocol Driver?
A. At client side, a separate driver is needed for each database.B. Type-4 driver is
entirely written in Java
C. The driver converts JDBC calls into vendor-specific database protocol
D. It does not support to read MySQL data.
ANSWER: A
8. Which driver is called as thin-driver in JDBC?
A. Type - 1.
B. Type - 4.
C. Type - 3.
D. Type - 2.
ANSWER: B
9. Several vendors are adding ...................... to their existing database .................
A) JDOBC, middle-ware products
B) JDBC drivers, upper-ware products
C) middle-ware products, JDOBC drivers

52
Advance Java Programming (17625)

D) JDBC drivers, middle-ware products


Answer: D
10. For execution of DELETE SQL query in JDBC, ............. method must be used.
A) executeQuery()
B) executeDeleteQuery()
C) executeUpdate()
D) executeDelete()
Answer:C
11. Prepared Statement object in JDBC used to execute........... queries.
A) Executable
B) Simple
C) High level
D) Parameterized
Answer:D
12. ODBC stands for
A) Object Data Binding Command
B) Open Database Console
C) Open Database Connectivity
D) Open Database Command
Answer:C
13. How many JDBC driver types does Sun define?
A. One
B. Two
C. Three
D. Four
Answer: Option D
14. Where is metadata stored in MySQL?
A. In the MySQL database metadata
B. In the MySQL database metasql
C. In the MySQL database mysql
D. None of the above is correct.
Answer: Option C
15. Which JDBC driver Type(s) can be used in either applet or servlet code?

53
Advance Java Programming (17625)

A. Both Type 1 and Type 2


B. Both Type 1 and Type 3
C. Both Type 3 and Type 4
D. Type 4 only
Answer: Option C

16. ________ is an open source DBMS product that runs on UNIX, Linux and Windows.
A.MySQL
B. JSP/SQL
C. JDBC/SQL
D.Sun ACCESS
Answer: Option A
17. Which JDBC driver Type(s) can you use in a three-tier architecture and if the Web
server and the DBMS are running on the same machine?
A. Type 1 only
B. Type 2 only
C. Both Type 3 and Type 4
D. All of Type 1, Type 2, Type 3 and Type 4
Answer: Option D
18. Which JDBC driver Type(s) is(are) the JDBC-ODBC bridge?
A. Type 1
B. Type 2
C. Type 3
D. Type 4
Answer: Option A
19. Which JDBC driver Types are for use over communications networks?
A. Type 3 only
B. Type 4 only
C. Both Type 3 and Type 4
D. Neither Type 3 nor Type 4
Answer: Option C
20. In JDBC ........................ imports all Java classes concerned with database
connectivity.

54
Advance Java Programming (17625)

A) javax.sql.*
B) java.mysql.*
C) java.sql.*
D) com.*
21. The JDBC API is used to invoke SQL commands directly?
A) TrueB) False
ANSWER: A) True
22. Why do you need the JDBC API?
A) ODBC is not appropriate for direct use from the Java programming language
because it uses a C interface
B) A literal translation of the ODBC C API into a Java API would not be desirable
C) ODBC is hard to learn
D) All mentioned above
ANSWER: D) All mentioned above
23. A JDBC technology-based driver ("JDBC driver") makes it possible to do?
A) Establish a connection with a data source
B) Send queries and update statements to the data source
C) Process the results
D) All mentioned above
ANSWER: D) All mentioned above
24. Which was first most widely used programming interface for accessing relational
databases, It offers the ability to connect to almost all databases on almost all
platforms.?
A) JDBC API
B) ODBC API
C) Both A & B
D) None of the above
ANSWER: B) ODBC API
25. Which models does JDBC API supports for database access?
A) Two-tier models
B) Three-tier models
C) Both A & B

55
Advance Java Programming (17625)

D) None of the above


ANSWER: C) Both A & B
26. In which model a Java applet or application talks directly to the data source?
A) Two-tier models
B) Three-tier models
C) Both A & B
D) None of the above
ANSWER: A) Two-tier models

27. The JDBC API is what allows access to a data source from a Java middle tier?
A) True
B) False
ANSWER: A) True
28. In which of the following JDBC a server technology are its support for?
A) Connection pooling
B) Distributed transactions
C) Disconnected rowsets
D) All mentioned above
ANSWER: D) All mentioned above
29. How many JDBC product components does the Java software provides?
A) 3
B) 2
C) 4
D) 5
ANSWER: A) 3
30. In the following which JDBC product components does the Java software provides?
A) the JDBC driver manager
B) the JDBC driver test suite
C) the JDBC-ODBC bridge
D) All mentioned above
ANSWER: D) All mentioned above
31. Which class has traditionally been the backbone of the JDBC architecture?
A) the JDBC driver manager

56
Advance Java Programming (17625)

B) the JDBC driver test suite


C) the JDBC-ODBC bridge
D) All mentioned above
ANSWER: A) the JDBC driver manager
32. Which provides some confidence that JDBC drivers will run your program?
A) the JDBC-ODBC bridge
B) the JDBC driver manager
C) the JDBC driver test suite
D) None of the above
ANSWER: C) the JDBC driver test suite
33. JDBC technology-based drivers generally fit into how many categories?
A) 4
B) 3
C) 2
D) 5
ANSWER: A) 4
34. Which kind of driver converts JDBC calls into calls on the client API for Oracle,
Sybase, Informix, IBM DB2, or other DBMS?
A) JDBC-ODBC bridge plus ODBC driver
B) Native-API partly-Java driver
C) JDBC-Net pure Java driver
D) Native-protocol pure Java driver
ANSWER: B) Native-API partly-Java driver
35. In which driver Network connection is indirect that a JDBC client makes to a
middleware process that acts as a bridge to the DBMS server?
A) JDBC-Net
B) JDBC-ODBC bridge
C) Native API as basis
D) Native protocol as basis
ANSWER: A) JDBC-Net
36. A leading database connectivity vendor, worked together to produce the?
A) JDBC-ODBC Bridge
B) JDBC Driver Test Suite

57
Advance Java Programming (17625)

C) Both A & B
D) None of the above
ANSWER: C) Both A & B
37. Which list gives a quick way to determine which Connection method is appropriate
for creating different types of SQL statements?
A) createStatement
B) PrepareStatement
C) prepareCall
D) All mentioned above
ANSWER: D) All mentioned above

38. Which method is used for an SQL statement that is executed frequently?
A) prepareStatement
B) prepareCall
C) createStatement
D) None of the above
ANSWER: A) prepareStatement
39. The ResultSet.next method is used to move to the next row of the ResultSet, making it
the current row?
A) True
B) False
ANSWER: A) True
40. How many Result sets available with the JDBC 2.0 core API, The following
constants, defined in the ResultSet interface, are used to specify these?
A) 2
B) 3
C) 4
D) 5
ANSWER: B) 3
41. In which the result set generally does not show changes to the underlying database
that are made while it is open. The membership, order, and column values of rows are
typically fixed when the result set is created?
A) TYPE_FORWARD_ONLY

58
Advance Java Programming (17625)

B) TYPE_SCROLL_INSENSITIVE
C) TYPE_SCROLL_SENSITIVE
D) ALL MENTIONED ABOVE
ANSWER: B) TYPE_SCROLL_INSENSITIVE
42. In concurrency which Indicates a result set that cannot be updated programmatically?
A) CONCUR_UPDATABLE
B) CONCUR_READ_ONLY
C) BOTH A & B
D) None of the above
ANSWER: B) CONCUR_READ_ONLY
43. Drivers that are JDBC Compliant should normally support scrollable result sets, but
they are not required to do so?
A) True
B) False
ANSWER: A) True
44. The intent is for JDBC drivers to implement nonscrollable result sets using the
support provided by the underlying database systems?
A) True
B) False
ANSWER: B) False
45. In order to transfer data between a database and an application written in the Java
programming language, the JDBC API provides which of these methods?
A) Methods on the ResultSet class for retrieving SQL SELECT results as Java types.
B) Methods on the PreparedStatement class for sending Java types as SQL statement
parameters.
C) Methods on the CallableStatement class for retrieving SQL OUT parameters as
Java types.
D) All mentioned above
ANSWER: D) All mentioned above
46. In which the JDBC type represents a "single precision" floating point number that
supports seven digits of mantissa?
A) REAL
B) DOUBLE

59
Advance Java Programming (17625)

C) FLOAT
D) INTEGER
ANSWER: A) REAL
47. The JDBC API has always supported persistent storage of objects defined in the Java
programming language through the methods getObject and setObject?
A) True
B) False
ANSWER: A) True
48. JDBC is a Java API that is used to connect and execute query to the database?
A) True B) False
ANSWER: A) True
49. Which of these API represents that software programs can follow to communicate
with each other?
A) Interfaces
B) Classes
C) Both A & B
D) None of the above
ANSWER: C) Both A & B
50. An API can be created for
A) applications
B) libraries
C) operating systems
D) All mentioned above
ANSWER: D) All mentioned above
51. How many types of JDBC drivers available?
A) 3 C) 2
B) 4 D) 5
ANSWER: B) 4
52. In the following JDBC drivers which is known as partially java driver?
A) JDBC-ODBC bridge driver
B) Native-API driver
C) Network Protocol driver

60
Advance Java Programming (17625)

D) Thin driver
ANSWER: B) Native-API driver
53. In the following JDBC drivers which are known as fully java driver?
A) Native-API driver
B) Network Protocol driver
C) Thin driver
D) Both B & C
ANSWER: D) Both B & C
54. Which driver uses ODBC driver to connect to the database?
A) JDBC-ODBC bridge driver
B) Native-API driver
C) Network Protocol driver
D) Thin driver
ANSWER: A) JDBC-ODBC bridge driver
55. Which driver converts JDBC calls directly into the vendor-specific database protocol?
A) Native-API driver
B) Network Protocol driver
C) Thin driver
D) Both B & C
ANSWER: C) Thin driver
56. Why java program cannot directly communicate with an ODBC driver?
A) ODBC written in C# language
B) ODBC written in C language
C) ODBC written in C++ language
D) None of the above
ANSWER: B) ODBC written in C language
57. How many steps are used to connect any java application with the database in java
using JDBC?
A) 5
B) 4
C) 3
D) 6
ANSWER: A) 5

61
Advance Java Programming (17625)

58. Which method of Class class is used to register the driver class, This method is used
to dynamically load the driver class?
A) forName()
B) getConnection()
C) createStatement()
D) executeQuery()
ANSWER: A) forName()
59. The default username for the oracle database is system?
A) True
B) False
ANSWER: A) True
60. Give the ways to set Temporary Path of JDK in Windows?
A) Open command prompt
B) copy the path of jdk/bin directory
C) write in command prompt: set path=copied_path
D) All mentioned above
ANSWER: D) All mentioned above
61. Abbrevate the term DSN?
A) Digital Source Name
D) Data Source Name
C) Data Socket Name
D) Data String Name
ANSWER: D) Data Source Name
62. The default username for the mysql database is?
A) System
B) root
C) Both A & B
D) None of the above
ANSWER: B) root
63. The following example to connect Java Application with access?
import java.sql.*;
class Test

62
Advance Java Programming (17625)

{
public static void main(String ar[])
{
try
{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSetrs=st.executeQuery("select * from login");
while(rs.next())
{
System.out.println(rs.getString(1));
}

}
catch(Exception ee){System.out.println(ee);}
}
}
A) With DSN
B) With out DSN
C) Both A & B
D) None of the above
ANSWER: A) With DSN
64. In DriverManager class which method is used to establish the connection with the
specified url?
A) public static void registerDriver(Driver driver)
B) public static void deregisterDriver(Driver driver)
C) public static Connection getConnection(String url)
D) public static Connection getConnection(String url,StringuserName,String
password)
ANSWER: C) public static Connection getConnection(String url)

63
Advance Java Programming (17625)

65. In Connection interface which method Drops all changes made since the previous
commit/rollback?
A) public void rollback()
B) public void commit()
C) public void close()
D) public Statement createStatement()
ANSWER: A) public void rollback()
66. Which interface provides methods to execute queries with the database?
A) Connection interface
B) Statement interface
C) ResultSet interface
D) None of the above
ANSWER: B) Statement interface

67. Which maintains a cursor pointing to a particular row of data,Initially, cursor points to
before the first row?
A) Connection interface
B) Statement interface
C) ResultSet interface
D) None of the above
ANSWER: C) ResultSet interface
68. ResultSet object can be moved forward only and it is updatable?
A) True
B) False
ANSWER: B) False
69. Which is used to execute parameterized query?
A) Statement interface
B) PreparedStatement interface
C) ResultSet interface
D) None of the above
ANSWER: B) PreparedStatement interface
70. The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once?

64
Advance Java Programming (17625)

A) True
B) False
ANSWER: A) True
71. This is an example of prepared statement interface that ?
PreparedStatementstmt=con.prepareStatement("select * from emp");
ResultSetrs=stmt.executeQuery();
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
A) deletes the record
B) retrieve the record
C) updates the record
D) inserts the record
ANSWER: B) retrieve the record
72. ResultSetMetaData interface is useful because it provides methods to get metadata
from the ResultSet object?
A) True
B) False
ANSWER: A) True
73. By using Which interface You can store images in the database in java by the help of?
A) PreparedStatement interface
B) ResultSetMetaData interface
C) DatabaseMetData interface
D) None of the above
ANSWER: A) PreparedStatement interface
74. Which is used to call the stored procedures and functions, CallableStatement
interface?
A) CallableStatement Interface
B) PreparedStatement Interface
C) Both A & B
D) None of the above
ANSWER: A) CallableStatement Interface

65
Advance Java Programming (17625)

75. The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once?
A) True
B) False
ANSWER: A) True
76. The ACID properties does not describes the transaction management well ?
A) True
B) False
ANSWER: B) False
77. JDBC stands for?
A) Java database connectivity
B) Java database concept
C) Java database communications
D) None of the above
ANSWER: A) Java database connectivity
78. In Transaction Management of JDBC which means once a transaction has been
committed, it will remain so, even in the event of errors, power loss etc.?
A) Atomicity
B) Isolation
C) Consistency
D) Durability
ANSWER: D) Durability
79. In Transaction Management in JDBC Transaction represents?
A) single unit of work
B) Multiple unit of work
C) Both A & B
D) None of the above
ANSWER: A) single unit of work
80. Which interfaces provide methods for batch processing in JDBC?
A) java.sql.Statement
B) java.sql.PreparedStatement
C) Both A & B

66
Advance Java Programming (17625)

D) None of the above


ANSWER: C) Both A & B
81. JDBC RowSet is the wrapper of ResultSet,It holds tabular data like ResultSet but it is
easy and flexible to use?
A) True
B) False
ANSWER: A) True
82. A Java program cannot directly communicate with an ODBC driver because .......
A) ODBC written in C language
B) ODBC written in C# language
C) ODBC written in C++ language
D) ODBC written in Basic language
Answer: a
83. The JDBC-ODBC Bridge driver translates the JDBC API to the ODBC API and used
with .......
A) JDBC drivers
B) ODBC drivers
C) Both A and B
D) None of the above
Answer: b
84. The .............................package contains classes that help in connecting to a database,
sending SQL statements to the database, and processing the query results.
A) connection.sql
B) db.sql
C) pkg.sql
D) java.sql
Answer: D.
85. The ................................method executes a simple query and returns a single Result
Set object.
A) executeUpdate()
B) executeQuery()
C) execute()

67
Advance Java Programming (17625)

D) noexecute()
Answer: B.
86. The ......................... method executes an SQL statement that may return multiple
results.
A) executeUpdate()
B) executeQuery()
C) execute()
D) noexecute()
Answer: C
87. The ........................ object allows you to execute parametrized queries.
A) ResultSet
B) Parametrized
C) PreparedStatement
D) Condition
Answer: C
88. The .................. object provides you with methods to access data from the table.
A) ResultSet
B) Parametrized
C) TableStatement
D) Condition
Answer: A
89. The parameters of the PreparedStatement object are ...................... when the user
clicks on the Query button.
A) initialized
B) started
C) paused
D) stopped
Answer: A
90. The ...................... method sets the query parameters of the PreparedStatement Object.
A) putString()
B) insertString()
C) setString()

68
Advance Java Programming (17625)

D) setToString()
Answer: C
91. Connection object can be initialized using the ............................ method of the Driver
Manager class.
A) putConnection()
B) setConnection()
C) Connection()
D) getConnetion()
Answer: D
92. Which type of driver is suited for database middleware?
A. Type 1
B. Type 2
C. Type 3
D. Type 4
ANSWER: C

69

You might also like