Chapter 4
Chapter 4
Chapter – 04 Marks: 20
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 )
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.
3
Advance Java Programming (17625)
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.
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)
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.
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");
}
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.
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
Statement:
13
Advance Java Programming (17625)
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");
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
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.
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)
25
Advance Java Programming (17625)
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)
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.
29
Advance Java Programming (17625)
30
Advance Java Programming (17625)
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
Miscellaneous Functions:
boolean wasNull ()
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
35
Advance Java Programming (17625)
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.
36
Advance Java Programming (17625)
int getYear ()
void setDate (int date)
void setMonth (int month)
void setTime (int time)
void SetYear (int year)
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:-
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 .
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.
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)
47
Advance Java Programming (17625)
48
Advance Java Programming (17625)
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.
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. . .
52
Advance Java Programming (17625)
53
Advance Java Programming (17625)
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)
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)
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)
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