You are on page 1of 13

JDBC

What is the query used to display all tables names in SQL Server (Query analyzer)?
Question (JDBC)

Answer select * from information_schema.tables


Question How many types of JDBC Drivers are present and what are they? (JDBC)
There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Answer Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver
Question What is the fastest type of JDBC driver? (JDBC)
JDBC driver performance will depend on a number of issues:
(a) the quality of the driver code,
(b) the size of the driver code,
(c) the database server and its load,
(d) network topology,
Answer
(e) the number of times your request is translated to a different API.
In general, all things being equal, you can assume that the more your request and
response change hands, the slower it will be. This means that Type 1 and Type 3 drivers
will be slower than Type 2 drivers (the database calls are make at least three translations
versus two), and Type 4 drivers are the fastest (only one translation).
Question What Class.forName will do while loading drivers? (JDBC)
It is used to create an instance of a driver and register it with the DriverManager.
Answer
When you have loaded a driver, it is available for making a connection with a DBMS.

Question How to Retrieve Warnings? (JDBC)


Answer SQLWarning objects are a subclass of SQLException that deal with database access
warnings. Warnings do not stop the execution of an application, as exceptions do; they
simply alert the user that something did not happen as planned. A warning can be
reported on a Connection object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these classes has a
getWarnings method, which you must invoke in order to see the first warning reported
on the calling object
E.g.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
Question what are stored procedures? How is it useful? (JDBC)
A stored procedure is a set of statements/commands which reside in the database. The
stored procedure is precompiled and saves the database the effort of parsing and
compiling sql statements everytime a query is run. Each Database has it's own stored
procedure language, usually a variant of C with a SQL preproceesor. Newer versions of
db's support writing stored procs in Java and Perl too.
Answer Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to
implement the business logic( A lot of systems still do it). The biggest advantage is of
course speed. Also certain kind of data manipulations are not achieved in SQL. Stored
procs provide a mechanism to do these manipulations. Stored procs are also useful
when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The
overhead of a JDBC Connection may be significant in these cases.
Question How to call a Stored Procedure from JDBC? (JDBC)
The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open Connection object. A
CallableStatement object contains a call to a stored procedure.
Answer
E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
Question Is the JDBC-ODBC Bridge multi-threaded? (JDBC)
No. The JDBC-ODBC Bridge does not support concurrent access from different
threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the
Answer
calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but
they won't get the advantages of multi-threading.
Does the JDBC-ODBC Bridge support multiple concurrent open statements per
Question
connection? (JDBC)
No. You can open only one Statement object per connection when you are using the
Answer
JDBC-ODBC Bridge.
Question What is cold backup, hot backup, warm backup recovery? (JDBC)
a. cold backup - All these files must be backed up at the same time, before the
databaseis restarted.
Answer
b. hot backup - official name is 'online backup' ? is a backup taken of each tablespace
while the database is running and is being accessed by the users.
Question When we will Denormalize data? (JDBC)
Data denormalization is reverse procedure, carried out purely for reasons
Answer of improving performance.It maybe efficient for a high-throughput system
to replicate data for certain data.
Question What is the advantage of using PreparedStatement? (JDBC)
If we are using PreparedStatement the execution time will be less.The
PreparedStatement object contains not just an SQL statement,but the SQL statement
Answer that has been precompiled.This means that when the PreparedStatement is executed,the
RDBMS can just run the PreparedStatement's Sql statement without having to compile
it first.
Question What is a "dirty read"? (JDBC)
Answer Quite often in database processing, we come across the situation wherein one
transaction can change a value, and a second transaction can read this value before the
original change has been committed or rolled back. This is known as a dirty read
scenario because there is always the possibility that the first transaction may rollback
the change, resulting in the second transaction having read an invalid value. While you
can easily command a database to disallow dirty reads, this usually degrades the
performance of your application due to the increased locking overhead. Disallowing
dirty reads also leads to decreased system concurrency.
Question What is Metadata and why should I use it? (JDBC)
Metadata ('data about data') is information about one of two things: Database
information (java.sql.DatabaseMetaData), or Information about a specific ResultSet
(java.sql.ResultSetMetaData).
Answer
Use DatabaseMetaData to find information about your database, such as its capabilities
and structure. Use ResultSetMetaData to find information about the results of an SQL
query, such as size and types of columns
Question Different types of Transaction Isolation Levels? (JDBC)
The isolation level describes the degree to which the data being updated is visible to
other transactions. This is important when two transactions are trying to read the same
row of a table. Imagine two transactions A & B.
Three types of inconsistencies can occur:
· Dirty-read: A has changed a row, but has not committed the changes. B reads the
uncommitted data but his view of the data may be wrong if A rolls back his changes and
updates his own changes to the database.
· Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B
reads the same row again, he will get different data.
· Phantoms: A does a query on a set of rows to perform an operation. B modifies the
Answer
table such that a query of A would have given a different result. The table may be
inconsistent.
TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE
READ AND PHANTOMS CAN OCCUR.
TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED,
NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE
READ ARE PREVENTED AND PHANTOMS CAN OCCUR.
TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ
AND PHANTOMS ARE PREVENTED.
Question What is 2 phase commit? (JDBC)
A 2-phase commit is an algorithm used to ensure the integrity of a committing
transactionIn Phase 1, the transaction coordinator contacts potential participants in the
transaction. The participants all agree to make the results of the transaction permanent
but do not do so immediately. The participants log information to disk to ensure they
Answer can complete Phase 2. If all the participants agree to commit, the coordinator logs that
agreement and the outcome is decided. The recording of this agreement in the log ends
Phase
In Phase 2, the coordinator informs each participant of the decision, and they
permanently update their resources.
Question How do you handle your own transaction ? (JDBC)
Connection Object has a method called setAutocommit ( Boolean istrue)
Answer - Default is true
Set the Parameter to false , and begin your transaction
Question What is the normal procedure followed by a java client to access the db.? (JDBC)
The database connection is created in 3 steps:
1.Find a proper database URL (see FAQ on JDBC URL)
2.Load the database driver
3.Ask the Java DriverManager class to open a connection to your database
In java code, the steps are realized in code as follows:
Answer 1.Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL
for more information). A JDBC URL has the form
jdbc:someSubProtocol://myDatabaseServer/theDatabaseName 2.
Class.forName("my.database.driver");
3 . Connection conn = DriverManager.getConnection("a.JDBC.URL",
"databaseLogin","databasePassword");
Question What is a data source? (JDBC)
A DataSource class brings another level of abstraction than directly using a connection
Answer object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file
System , any DBMS etc.
Question What are collection pools? What are the advantages? (JDBC)
A connection pool is a cache of database connections that is maintained in memory, so
Answer
that the connections may be reused
How do you get Column names only for a table (SQL Server)? Write the
Question
Query. (JDBC)
select name from syscolumns where id=(select id from sysobjects where
Answer
name='user_hdr') order by colid --user_hdr is the table name
Question What is the difference between cached rowset, jdbrowset and webrowset? (JDBC)
A CachedRowSet is a disconnected, serializable, scrollable container for tabular data.
A primary purpose of the CachedRowSet class is to provide a representation of a JDBC
ResultSet that can be passed between different components of a distributed application.
For example, a CachedResultSet can be used to send the result of a query executed by
an Enterprise JavaBeans component running in a server environment over a network to
a client running in a web browser. A second use for CachedRowSets is to provide
scrolling and updating for ResultSets that don't provide these capabilities themselves. A
CachedRowSet can be used to augment the capabilities of a JDBC driver that doesn't
have full support for scrolling and updating. Finally, a CachedRowSet can be used to
Answer provide Java applications with access to tabular data in an environment such as a thin
client or PDA, where it would be inappropriate to use a JDBC driver due to resource
limitations or security considerations. The CachedRowSet class provides a means to
"get rows in" and "get changed rows out" without the need to implement the full JDBC
API.
A JdbcRowSet is a connected rowset that wraps a ResultSet object. The main use of
JdbcRowSet is to wrap a ResultSet and make it appear as a JavaBeans(tm) component.
The WebRowSet class extends CachedRowSet with the ability to write out the state of
the the RowSet as an XML document. The format of the XML document is described
by the DTD 'RowSet.dtd'.
Question Is thin driver provided by Oracle a type 4 driver? (JDBC)
Answer YES
What are different types of isolation levels in JDBC and explain where you can use
Question
them? (JDBC)
Answer If the application needs only committed records, then
TRANSACTION_READ_COMMITED isolation is the good choice.
If the application needs to read a row exclusively till you finish your work, then
TRANSACTION_REPEATABLE_READ is the best choice.
If the application needs to control all of the transaction problems(dirty read, phantom
read and unrepeatable read), you can choose TRANSACTION_SERIALIZABLE for
maximum safety. Performance issues have to be taken care with this. E.g Banking
applications.
If the application don't have to deal with concurrent transactions, then the best choice is
TRANSACTION_NONE to improve performance.
If the application is searching for records from the database then you can easily choose
TRANSACTION_READ_UNCOMMITED because you need not worry about other
programmes that are inserting records at the same time. It improves performance.
What is the difference between Statement, PreparedStatement and CallableStatemen?
Question (JDBC)

Statement is used for static SQL statement with no input and output parameters,
PreparedStatement is used for dynamic SQL statement with input parameters and
CallableStatement is used for dynamic SQL satement with both input and output
parameters, but PreparedStatement and CallableStatement can be used for static SQL
statements as well. CallableStatement is mainly meant for stored procedures.

PreparedStatement gives better performance when compared to Statement because it is


pre-parsed and pre-compiled by the database once for the first time and then onwards it
reuses the parsed and compiled statement. Because of this feature, it significantly
Answer
improves performance when a statement executes repeatedly, It reduces the overload
incurred by parsing and compiling.

CallableStatement gives better performance when compared to PreparedStatement and


Statement when there is a requirement for single request to process multiple complex
statements. It parses and stores the stored procedures in the database and does all the
work at database itself that in turn improves performance. But we loose java portability
and we have to depend up on database specific stored procedures.

1. What is JDBC?

JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a
layer of abstraction that allows users to choose between databases. It allows you to
change to a different database engine and to write to a single API. JDBC allows you to
write database applications in Java without having to concern yourself with the
underlying details of a particular database.

2. What are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation


interface for application and applet writers.

3. What is JDBC Driver interface?


The JDBC Driver interface provides vendor-specific implementations of the abstract
classes provided by the JDBC API. Each vendors driver must provide implementations
of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet
and Driver.

4. What are the common tasks of JDBC?


o Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
o Register a driver
o Specify a database
o Open a database connection
o Submit a query
o Receive results
5. How to use JDBC to connect Microsoft Access?

Please see this page for detailed information.

6. What are four types of JDBC driver?

1.Type 1 Drivers

Bridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such
as ODBC to transfer the SQL calls to the database and also often rely on native
code.

2.Type 2 Drivers

Use the existing database API to communicate with the database on the client.
Faster than Type 1, but need native code and require additional permissions to
work in an applet. Good for client-side connection.

3.Type 3 Drivers

Call the database API on the server.Flexible. Pure Java and no native code.

4.Type 4 Drivers

The hightest level of driver reimplements the database network API in Java. No
native code.

2. What packages are used by JDBC?

There are at least 8 packages:

1.java.sql.Driver
2.Connection
3.Statement
4.PreparedStatement
5.CallableStatement
6.ResultSet
7.ResultSetMetaData
8.DatabaseMetaData
3. There are three basic types of SQL statements, what are they?
1.Statement
2.callableStatement
3.PreparedStatement
4. What are the flow statements of JDBC?

A URL string -->getConnection-->DriverManager-->Driver-->Connection--


>Statement-->executeQuery-->ResultSet.

5. What are the steps involved in establishing a connection?

This involves two steps: (1) loading the driver and (2) making the connection.

6. How can you load the drivers?

Loading the driver or drivers you want to use is very simple and involves just one line
of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following
code will load it:

Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use. For instance, if the class
name is jdbc.DriverXYZ , you would load the driver with the following line of code:

E.g.
Class.forName("jdbc.DriverXYZ");

7. What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When
you have loaded a driver, it is available for making a connection with a DBMS.

8. How can you make the connection?

In establishing a connection is to have the appropriate driver connect to the DBMS. The
following line of code illustrates the general idea:

E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

9. How can you create JDBC statements?

A Statement object is what sends your SQL statement to the DBMS. You simply create
a Statement object and then execute it, supplying the appropriate execute method with
the SQL statement you want to send. For a SELECT statement, the method to use is
executeQuery. For statements that create or modify tables, the method to use is
executeUpdate. E.g. It takes an instance of an active connection to create a Statement
object. In the following example, we use our Connection object con to create the
Statement object stmt :

Statement stmt = con.createStatement();

10. How to make a query?

Create a Statement object and calls the Statement.executeQuery method to select data
from the database. The results of the query are returned in a ResultSet object.

Statement stmt = con.createStatement();


ResultSet results = stmt.executeQuery("SELECT data FROM aDatabase ");

11. How can you retrieve data from the ResultSet?

Use get methods to retrieve data from returned ResultSet object.

ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");


String s = rs.getString("COF_NAME");

The method getString is invoked on the ResultSet object rs , so getString will retrieve
(get) the value stored in the column COF_NAME in the current row of rs

12. How to navigate the ResultSet?

By default the result set cursor points to the row before the first row of the result set. A
call to next() retrieves the first result set row. The cursor can also be moved by calling
one of the following ResultSet methods:

o beforeFirst(): Default position. Puts cursor before the first row of the result set.
o first(): Puts cursor on the first row of the result set.
o last(): Puts cursor before the last row of the result set.
o afterLast() Puts cursor beyond last row of the result set. Calls to previous moves
backwards through the ResultSet.
o absolute(pos): Puts cursor at the row number position where absolute(1) is the
first row and absolute(-1) is the last row.
o relative(pos): Puts cursor at a row relative to its current position where relative(1)
moves row cursor one row forward.

7. What are the different types of Statements?

1. Statement (use createStatement method)


2. Prepared Statement (Use prepareStatement method)
3. Callable Statement (Use prepareCall)
2. If you want to use the percent sign (%) as the percent sign and not have it
interpreted as the SQL wildcard used in SQL LIKE queries, how to do that?
Use escape keyword. For example:

stmt.executeQuery("select tax from sales where tax like '10\%' {escape '\'}");

3. How to escape ' symbol found in the input line?

You may use a method to do so:

static public String escapeLine(String s) {


String retvalue = s;
if (s.indexOf ("'") != -1 ) {
StringBuffer hold = new StringBuffer();
char c;
for(int i=0; i < s.length(); i++ ) {
if ((c=s.charAt(i)) == '\'' ) {
hold.append ("''");
}else {
hold.append(c);
}
}
retvalue = hold.toString();
}
return retvalue;
}

Note that such method can be extended to escape any other characters that the database
driver may interprete another way.

4. How to make an update?

Creates a Statement object and calls the Statement.executeUpdate method.

String updateString = "INSERT INTO aDatabase VALUES (some text)";


int count = stmt.executeUpdate(updateString);

5. How to update a ResultSet?

You can update a value in a result set by calling the ResultSet.update method on the row
where the cursor is positioned. The type value here is the same used when retrieving a
value from the result set, for example, updateString updates a String value and
updateDouble updates a double value in the result set.

rs.first();
updateDouble("balance", rs.getDouble("balance") - 5.00);

The update applies only to the result set until the call to rs.updateRow(), which updates
the underlying database.
To delete the current row, use rs.deleteRow().

To insert a new row, use rs.moveToInsertRow().

6. How can you use PreparedStatement?

This special type of statement is derived from the more general class, Statement. If you
want to execute a Statement object many times, it will normally reduce execution time
to use a PreparedStatement object instead. The advantage to this is that in most cases,
this SQL statement will be sent to the DBMS right away, where it will be compiled. As
a result, the PreparedStatement object contains not just an SQL statement, but an SQL
statement that has been precompiled. This means that when the PreparedStatement is
executed, the DBMS can just run the PreparedStatement 's SQL statement without
having to compile it first.

PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET


SALES = ? WHERE COF_NAME LIKE ?");

7. How to call a Stored Procedure from JDBC?

The first step is to create a CallableStatement object. As with Statement an and


PreparedStatement objects, this is done with an open Connection object. A
CallableStatement object contains a call to a stored procedure;

E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

8. How to Retrieve Warnings?

SQLWarning objects are a subclass of SQLException that deal with database access
warnings. Warnings do not stop the execution of an application, as exceptions do; they
simply alert the user that something did not happen as planned. A warning can be
reported on a Connection object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these classes has a
getWarnings method, which you must invoke in order to see the first warning reported
on the calling object

SQLWarning warning = stmt.getWarnings();


if (warning != null) {

while (warning != null) {


System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
9. How to Make Updates to Update ResultSets?

Another new feature in the JDBC 2.0 API is the ability to update rows in a result set
using methods in the Java programming language rather than having to send an SQL
command. But before you can take advantage of this capability, you need to create a
ResultSet object that is updatable. In order to do this, you supply the ResultSet constant
CONCUR_UPDATABLE to the createStatement method.

Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");


Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");

10. How to set a scroll type?

Both Statements and PreparedStatements have an additional constructor that accepts a


scroll type and an update type parameter. The scroll type value can be one of the
following values:

o ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC 1.0, application


can only call next() on the result set.
o ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and updates are
reflected in the result set as they occur.
o ResultSet.SCROLL_INSENSITIVE Result set is fully navigable, but updates are
only visible after the result set is closed. You need to create a new result set to see
the results.

8. How to set update type parameter?

In the constructors of Statements and PreparedStatements, you may use

o ResultSet.CONCUR_READ_ONLY The result set is read only.


o ResultSet.CONCUR_UPDATABLE The result set can be updated.

You may verify that your database supports these types by calling
con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

9. How to do a batch job?

By default, every JDBC statement is sent to the database individually. To send multiple
statements at one time , use addBatch() method to append statements to the original
statement and call executeBatch() method to submit entire statement.

Statement stmt = con.createStatement();


stmt.addBatch("update registration set balance=balance-5.00 where theuser="+theuser);
stmt.addBatch("insert into auctionitems(description, startprice)
values("+description+","+startprice+")");
...
int[] results = stmt.executeBatch();

The return result of the addBatch() method is an array of row counts affected for each
statement executed in the batch job. If a problem occurred, a
java.sql.BatchUpdateException is thrown. An incomplete array of row counts can be
obtained from BatchUpdateException by calling its getUpdateCounts() method.

10. How to store and retrieve an image?

To store an image, you may use the code:

int itemnumber=400456;

File file = new File(itemnumber+".jpg");


FileInputStream fis = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("update auctionitems set theimage=?
where id= ?");
pstmt.setBinaryStream(1, fis, (int)file.length()):
pstmt.setInt(2, itemnumber);
pstmt.executeUpdate();
pstmt.close();
fis.close();

To retrieve an image:

int itemnumber=400456;
byte[] imageBytes;//hold an image bytes to pass to createImage().

PreparedStatement pstmt = con.prepareStatement("select theimage from auctionitems


where id= ?");
pstmt.setInt(1, itemnumber);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
imageBytes = rs.getBytes(1);
}
pstmt.close();
rs.close();

Image auctionimage = Toolkit.getDefaultToolkit().createImage(imageBytes);

11. How to store and retrive an object?

A class can be serialized to a binary database field in much the same way as the image.
You may use the code above to store and retrive an object.

12. How to use meta data to check a column type?


Use getMetaData().getColumnType() method to check data type. For example to
retrieve an Integer, you may check it first:

int count=0;
Connection con=getConnection();
Statement stmt= con.createStatement();
stmt.executeQuery("select counter from aTable");
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
if(rs.getMetaData().getColumnType(1) == Types.INTEGER) {
Integer i=(Integer)rs.getObject(1);
count=i.intValue();
}
}
rs.close();

13. Why cannot java.util.Date match with java.sql.Date?

Because java.util.Date represents both date and time. SQL has three types to represent
date and time.

o java.sql.Date -- (00/00/00)
o java.sql.Time -- (00:00:00)
o java.sql.Timestamp -- in nanoseconds

Note that they are subclasses of java.util.Date.

14. How to convert java.util.Date value to java.sql.Date?

Use the code below:

Calendar currenttime=Calendar.getInstance();
java.sql.Date startdate= new java.sql.Date((currenttime.getTime()).getTime());

or

SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");


java.util.Date enddate = new java.util.Date("10/31/99");
java.sql.Date sqlDate = java.sql.Date.valueOf(template.format(enddate));

You might also like