|
Technical Interview Questions
Javascript Interview Questions
Oracle Interview Questions
J2EE Interview Questions
C++
Interview Questions
XML
Interview Questions
EJB
Interview Questions
JSP
Interview Questions
.........More
Programming Source Codes
Java Source Codes
Html Source Codes
CSS Source Codes
C Source Codes
.........More
Soft Skills
Communication Skills
Leadership Skills
.........More
|
|
JDBC Interview Questions and Answers
How can I get data from multiple ResultSets?
With certain database systems, a stored procedure can
return multiple result sets, multiple update counts, or
some combination of both. Also, if you are providing a
user with the ability to enter any SQL statement, you
don't know if you are going to get a ResultSet or an
update count back from each statement, without analyzing
the contents. The Statement.execute() method helps in
these cases.
Method Statement.execute() returns a boolean to tell you
the type of response:
* true indicates next result is a ResultSet
Use Statement.getResultSet to get the ResultSet
* false indicates next result is an update count
Use Statement.getUpdateCount to get the update count
* false also indicates no more results
Update count is -1 when no more results (usually 0 or
positive)
After processing each response, you use
Statement.getMoreResults to check for more results,
again returning a boolean. The following demonstrates
the processing of multiple result sets:
boolean result = stmt.execute(" ... ");
int updateCount = stmt.getUpdateCount();
while (result || (updateCount != -1)) {
if(result) {
ResultSet r = stmt.getResultSet();
// process result set
} else if(updateCount != -1) {
// process update count
}
result = stmt.getMoreResults();
updateCount = stmt.getUpdateCount();
}
How can resultset records be restricted to certain rows?
The easy answer is "Use a JDBC 2.0 compliant driver".
With a 2.0 driver, you can use the setFetchSize() method
within a Statement or a ResultSet object.
For example,
Statement stmt = con.createStatement();
stmt.setFetchSize(400);
ResultSet rs = stmt.executeQuery("select * from
customers");
will change the default fetch size to 400.
You can also control the direction in which the rows are
processed. For instance:
stmt.setFetchDirection(ResultSet.FETCH_REVERSE)
will process the rows from bottom up.
The driver manager usually defaults to the most
efficient fetch size...so you may try experimenting with
different value for optimal performance.
How do I insert an image file (or other raw data) into a
database?
All raw data types (including binary documents or
images) should be read and uploaded to the database as
an array of bytes, byte[]. Originating from a binary
file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of
java.sql.PreparedStatement to upload the data.
How can I connect from an applet to a database on the
server?
There are two ways of connecting to a database on the
server side.
1. The hard way. Untrusted applets cannot touch the hard
disk of a computer. Thus, your applet cannot use native
or other local files (such as JDBC database drivers) on
your hard drive. The first alternative solution is to
create a digitally signed applet which may use locally
installed JDBC drivers, able to connect directly to the
database on the server side.
2. The easy way. Untrusted applets may only open a
network connection to the server from which they were
downloaded. Thus, you must place a database listener
(either the database itself, or a middleware server) on
the server node from which the applet was downloaded.
The applet would open a socket connection to the
middleware server, located on the same computer node as
the webserver from which the applet was downloaded. The
middleware server is used as a mediator, connecting to
and extract data from the database.
Can I use the JDBC-ODBC bridge driver in an applet?
Short answer: No.
Longer answer: You may create a digitally signed applet
using a Certicate to circumvent the security sandbox of
the browser.
Which is the preferred collection class to use for
storing database result sets?
When retrieving database results, the best collection
implementation to use is the LinkedList. The benefits
include:
* Retains the original retrieval order
* Has quick insertion at the head/tail
* Doesn't have an internal size limitation like a Vector
where when the size is exceeded a new internal structure
is created (or you have to find out size beforehand to
size properly)
* Permits user-controlled synchronization unlike the
pre-Collections Vector which is always synchronized
Basically:
ResultSet result = stmt.executeQuery("...");
List list = new LinkedList();
while(result.next()) {
list.add(result.getString("col"));
}
If there are multiple columns in the result set, you'll
have to combine them into their own data structure for
each row. Arrays work well for that as you know the
size, though a custom class might be best so you can
convert the contents to the proper type when extracting
from databse, instead of later.
The java.sql package contains mostly interfaces. When
and how are these interfaces implemented while
connecting to database?
The implementation of these interfaces is all part of
the driver. A JDBC driver is not just one class - it is
a complete set of database-specific implementations for
the interfaces defined by the JDBC.
These driver classes come into being through a bootstrap
process. This is best shown by stepping through the
process of using JDBC to connect to a database, using
Oracle's type 4 JDBC driver as an example:
* First, the main driver class must be loaded into the
VM:
Class.forName("oracle.jdbc.driver.OracleDriver");
The specified driver must implement the Driver
interface. A class initializer (static code block)
within the OracleDriver class registers the driver with
the DriverManager.
* Next, we need to obtain a connection to the database:
String jdbcURL = "jdbc:oracle:thin:@www.jguru.com:1521:ORCL";
Connection connection =
DriverManager.getConnection(jdbcURL);
DriverManager determines which registered driver to use
by invoking the acceptsURL(String url) method of each
driver, passing each the JDBC URL. The first driver to
return "true" in response will be used for this
connection. In this example, OracleDriver will return
"true", so DriverManager then invokes the connect()
method of OracleDriver to obtain an instance of
OracleConnection. It is this database-specific
connection instance implementing the Connection
interface that is passed back from the
DriverManager.getConnection() call.
* The bootstrap process continues when you create a
statement:
Statement statement = connection.createStatement();
The connection reference points to an instance of
OracleConnection. This database-specific implementation
of Connection returns a database-specific implementation
of Statement, namely OracleStatement
* Invoking the execute() method of this statement object
will execute the database-specific code necessary to
issue an SQL statement and retrieve the results:
ResultSet result = statement.executeQuery("SELECT * FROM
TABLE");
Again, what is actually returned is an instance of
OracleResultSet, which is an Oracle-specific
implementation of the ResultSet interface.
So the purpose of a JDBC driver is to provide these
implementations that hide all the database-specific
details behind standard Java interfaces.
How can I manage special characters (for example: " _ '
% ) when I execute an INSERT query? If I don't filter
the quoting marks or the apostrophe, for example, the
SQL string will cause an error.
In JDBC, strings containing SQL commands are just normal
strings - the SQL is not parsed or interpreted by the
Java compiler. So there is no special mechanism for
dealing with special characters; if you need to use a
quote (") within a Java string, you must escape it.
The Java programming language supports all the standard
C escapes, such as \n for newline, \t for tab, etc. In
this case, you would use \" to represent a quote within
a string literal:
String stringWithQuote =
"\"No,\" he replied, \"I did not like that salted
licorice.\"";
This only takes care of one part of the problem: letting
us control the exact string that is passed on to the
database. If you want tell the database to interpret
characters like a single quote (') literally (and not as
string delimiters, for instance), you need to use a
different method. JDBC allows you to specify a separate,
SQL escape character that causes the character following
to be interpreted literally, rather than as a special
character.
An example of this is if you want to issue the following
SQL command:
SELECT * FROM BIRDS
WHERE SPECIES='Williamson's Sapsucker'
In this case, the apostrophe in "Williamson's" is going
to cause a problem for the database because SQL will
interpret it as a string delimiter. It is not good
enough to use the C-style escape \', because that
substitution would be made by the Java compiler before
the string is sent to the database.
Different flavors of SQL provide different methods to
deal with this situation. JDBC abstracts these methods
and provides a solution that works for all databases.
With JDBC you could write the SQL as follows:
Statement statement = // obtain reference to a Statement
statement.executeQuery(
"SELECT * FROM BIRDS WHERE SPECIES='Williamson/'s
Sapsucker' {escape '/'}");
The clause in curly braces, namely {escape '/'}, is
special syntax used to inform JDBC drivers what
character the programmer has chosen as an escape
character. The forward slash used as the SQL escape has
no special meaning to the Java compiler; this escape
sequence is interpreted by the JDBC driver and
translated into database-specific SQL before the SQL
command is issued to the database.
Escape characters are also important when using the SQL
LIKE clause. This usage is explicitly addressed in
section 11.5 of the JDBC specification:
The characters "%" and "_" have special meaning in SQL
LIKE clauses (to match zero or more characters, or
exactly one character, respectively). In order to
interpret them literally, they can be preceded with a
special escape character in strings, e.g. "\". In order
to specify the escape character used to quote these
characters, include the following syntax on the end of
the query:
{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape
'\'}
finds identifier names that begin with an underbar.
Page Numbers :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Have a Question ?
post your questions here. It
will be answered as soon as possible.
Check
Java Interview
Questions for more Java Interview Questions with answers
Check
Structs Interview
Questions for more Structs Interview Questions with answers
Check
Servlet Interview
Questions for more Servlet Interview Questions with answers
|