Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

151.

What Is The Difference Between Setmaxrows(int) And Setfetchsize(int)? Can Either Reduce Processing Time?

Answer»

SETFETCHSIZE(INT) defines the number of ROWS that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.

setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method MAY not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit. Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. ALWAYS refer to the driver documentation.

setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.

setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit. Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. Always refer to the driver documentation.

152.

What Is Jdo?

Answer»

JDO PROVIDES for the transparent persistence of DATA in a data store agnostic manner, SUPPORTING OBJECT, hierarchical, as WELL as relational stores.

JDO provides for the transparent persistence of data in a data store agnostic manner, supporting object, hierarchical, as well as relational stores.

153.

What's The Best Way, In Terms Of Performance, To Do Multiple Insert/update Statements, A Preparedstatement Or Batch Updates?

Answer»

Because PreparedStatement objects are precompiled, their execution can be faster than that of STATEMENT objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. A CallableStatement object PROVIDES a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object. Batch updates are USED when you want to execute MULTIPLE statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method.

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. A CallableStatement object provides a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object. Batch updates are used when you want to execute multiple statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method.

154.

I Need To Have Result Set On A Page Where The User Can Sort On The Column Headers. Any Ideas?

Answer»

One possibility: Have an optional field in your form or GET url called (appropriately) ORDER with a default value of either "no order" or whatever you want your default ordering to be (i.e. timestamp, username, whatever). When you get your REQUEST, see what the value of the ORDER element is. If it's null or blank, USE the default. Use that value to build your SQL query, and display the results to the page. If you're caching DATA in your servlet, you can use the Collection framework to SORT your data (see java.util.Collections) if you can get it into a LIST format. Then, you can create a Collator which can impose a total ordering on your results.

One possibility: Have an optional field in your form or GET url called (appropriately) ORDER with a default value of either "no order" or whatever you want your default ordering to be (i.e. timestamp, username, whatever). When you get your request, see what the value of the ORDER element is. If it's null or blank, use the default. Use that value to build your SQL query, and display the results to the page. If you're caching data in your servlet, you can use the Collection framework to sort your data (see java.util.Collections) if you can get it into a List format. Then, you can create a Collator which can impose a total ordering on your results.

155.

What Are The Components Of The Jdbc Url For Oracle's "thin" Driver And How Do I Use Them?

Answer»

Briefly: jdbc:oracle:THIN:@hostname:port:oracle-sid

  1. in green the Oracle sub-protocol (can be oracle:oci7:@, oracle:oci8:@, racle:thin:@, etc...) is RELATED on the driver you are UNSIGN and the protocol to communicate with server.
  2. in red the network machine name, or its ip ADDRESS, to locate the server where oracle is running.
  3. in blue the port (it is complementary to the address to select the specific oracle service)
  4. in magenta the sid, select on which database you want to CONNECT.
example:
jdbc:oracle:thin:@MyOracleHost:1521:MyDB
Here's an example:
jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDB
where user=scott and pass=tiger.

Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid

156.

How Can I Get Data From Multiple Resultsets?

Answer»

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();
}

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:

Use Statement.getResultSet to get the ResultSet

Use Statement.getUpdateCount to get the update count

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:

157.

Which Is The Preferred Collection Class To Use For Storing Database Result Sets?

Answer»

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.

When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include:

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.

158.

How Do I Extract A Blob From A Database?

Answer»

A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You EXTRACT the data in two steps:

  1. Call the getBlob method of the Statement class to retrieve a java.sql.Blob object.
  2. Call either getBinaryStream or getBytes in the extracted Blob object to retrieve the java byte[] which is the Blob object.

Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. THUS, you must extract all data from the database blob before calling commit or

<div align="center">
private void runGetBLOB()
{
try
{ // Prepare a Statement:
PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");
// Execute
ResultSet rs = stmnt.executeQuery();
while(rs.next())
{
try
{
// Get as a BLOB
Blob aBlob = rs.getBlob(1);
byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length());
}
catch(Exception EX)
{
// The driver could not HANDLE this as a BLOB...
// Fallback to default (and slower) byte[] handling
byte[] bytes = rs.getBytes(1);
}
}
// Close resources rs.close();
stmnt.close();
}
catch(Exception ex)
{
this.log("ERROR when trying to read BLOB: " + ex);
}
}</div>

A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You extract the data in two steps:

Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. Thus, you must extract all data from the database blob before calling commit or

159.

How Do I Check What Table Types Exist In A Database?

Answer»

USE the getTableTypes method of interface java.sql.DatabaseMetaData to PROBE the database for table types. The exact usage is described in the CODE below.

public static void main(String[] ARGS) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all table types.
ResultSet rs = dbmd.getTableTypes();
// Printout table data
while(rs.next())
{
// Printout
System.out.println("TYPE: " + rs.getString(1));
}
// Close database resources
rs.close();
conn.close();
}

Use the getTableTypes method of interface java.sql.DatabaseMetaData to probe the database for table types. The exact usage is described in the code below.

160.

How Do I Find All Database Stored Procedures In A Database?

Answer»

Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection CONN = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// GET DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all procedures.
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedures(null, null, "%");
// PRINTOUT table data
while(rs.next())
{
// Get PROCEDURE metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbProcedureRemarks = rs.getString(7);
short dbProcedureType = rs.getShort(8);
// Make result readable for humans
String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");
// Printout
System.out.println("Procedure: " + dbProcedureName + ", RETURNS: " + procReturn);
System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]");
System.out.println(" Comments: " + dbProcedureRemarks);
}
// Close database resources
rs.close();
conn.close();
}

Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.

161.

How Can I Investigate The Physical Structure Of A Database?

Answer»

The JDBC view of a database internal structure can be seen in the image below.

  • Several database objects (tables, views, procedures etc.) are contained within a Schema.
  • Several schema (user namespaces) are contained within a catalog.
  • Several catalogs (database partitions; databases) are contained within a DB server (such as Oracle, MS SQL.

The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:

public STATIC void main(String[] args) throws Exception
{
// LOAD the database driver - in this CASE, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// GET DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all Catalogs
System.out.println("nCatalogs are called '" + dbmd.getCatalogTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());
// Get all Schemas
System.out.println("nSchemas are called '" + dbmd.getSchemaTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());
// Get all Table-like types
System.out.println("NALL table types supported in this RDBMS:");
processResultSet("Table type", dbmd.getTableTypes());
// Close the Connection
conn.close();
}
public static void processResultSet(String preamble, ResultSet rs)
throws SQLException
{
// Printout table data
while(rs.next())
{
// Printout
System.out.println(preamble + ": " + rs.getString(1));
}
// Close database resources
rs.close();
}

The JDBC view of a database internal structure can be seen in the image below.

The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:

162.

What Jdbc Objects Generate Sqlwarnings?

Answer»

Connections, Statements and ResultSets all have a getWarnings method that allows RETRIEVAL. Keep in mind that prior ResultSet warnings are cleared on each NEW read and prior STATEMENT warnings are cleared with each new execution. getWarnings() itself does not clear EXISTING warnings, but each OBJECT has a clearWarnings method.

Connections, Statements and ResultSets all have a getWarnings method that allows retrieval. Keep in mind that prior ResultSet warnings are cleared on each new read and prior Statement warnings are cleared with each new execution. getWarnings() itself does not clear existing warnings, but each object has a clearWarnings method.

163.

What Does Normalization Mean For Java.sql.date And Java.sql.time?

Answer»

These classes are thin WRAPPERS extending java.util.Date, which has both date and time COMPONENTS. java.sql.Date should CARRY only date information and a NORMALIZED instance has the time information set to zeros. java.sql.Time should carry only time information and a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the milliseconds portion set to zero.

These classes are thin wrappers extending java.util.Date, which has both date and time components. java.sql.Date should carry only date information and a normalized instance has the time information set to zeros. java.sql.Time should carry only time information and a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the milliseconds portion set to zero.

164.

What Scalar Functions Can I Expect To Be Supported By Jdbc?

Answer»

JDBC supports NUMERIC, string, time, date, system, and conversion functions on scalar values. For a list of those supported and additional information, see SECTION A.1.4 Support Scalar Functions in the JDBC Data Access API For DRIVER Writers. Note that drivers are only EXPECTED to support those scalar functions that are supported by the underlying DB engine.

JDBC supports numeric, string, time, date, system, and conversion functions on scalar values. For a list of those supported and additional information, see section A.1.4 Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note that drivers are only expected to support those scalar functions that are supported by the underlying DB engine.

165.

What Does Setfetchsize() Really Do?

Answer»

The API documentation explains it pretty well, but a number of programmers seem to have a misconception of its functionality. The first thing to NOTE is that it may do nothing at all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is really a request for a certain sized blocking factor, that is, how much DATA to send at a time.

Because trips to the server are expensive, sending a larger number of rows can be more efficient. It may be more efficient on the server side as well, depending on the particular SQL statement and the DB engine. That would be true if the data could be read straight off an index and the DB engine paid attention to the fetch size. In that case, the DB engine could return only enough data per request to match the fetch size. Don't COUNT on that behavior. In general, the fetch size will be transparent to your program and only determines how often requests are sent to the server as you traverse the data. Also, both Statement and ResultSet have setFetchSize METHODS. If used with a Statement, all ResultSets RETURNED by that Statement will have the same fetch size. The method can be used at any time to change the fetch size for a given ResultSet. To determine the current or default size, use the getFetchSize methods.

The API documentation explains it pretty well, but a number of programmers seem to have a misconception of its functionality. The first thing to note is that it may do nothing at all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is really a request for a certain sized blocking factor, that is, how much data to send at a time.

Because trips to the server are expensive, sending a larger number of rows can be more efficient. It may be more efficient on the server side as well, depending on the particular SQL statement and the DB engine. That would be true if the data could be read straight off an index and the DB engine paid attention to the fetch size. In that case, the DB engine could return only enough data per request to match the fetch size. Don't count on that behavior. In general, the fetch size will be transparent to your program and only determines how often requests are sent to the server as you traverse the data. Also, both Statement and ResultSet have setFetchSize methods. If used with a Statement, all ResultSets returned by that Statement will have the same fetch size. The method can be used at any time to change the fetch size for a given ResultSet. To determine the current or default size, use the getFetchSize methods.

166.

Is There A Practical Limit For The Number Of Sql Statements That Can Be Added To An Instance Of A Statement Object

Answer»

While the specification makes no mention of any size LIMITATION for Statement.addBatch(), this seems to be dependent, as usual, on the driver. Among other things, it depends on the type of container/collection used. I know of at least ONE driver that uses a Vector and grows as needed. I've seen questions about another driver that APPEARS to peak somewhere between 500 and 1000 statements. Unfortunately, there doesn't appear to be any metadata information regarding possible limits. Of course, in a production quality driver, one would expect an exception from an addBatch() invocation that went BEYOND the command list's limits.

While the specification makes no mention of any size limitation for Statement.addBatch(), this seems to be dependent, as usual, on the driver. Among other things, it depends on the type of container/collection used. I know of at least one driver that uses a Vector and grows as needed. I've seen questions about another driver that appears to peak somewhere between 500 and 1000 statements. Unfortunately, there doesn't appear to be any metadata information regarding possible limits. Of course, in a production quality driver, one would expect an exception from an addBatch() invocation that went beyond the command list's limits.

167.

How Can I Determine Whether A Statement And Its Resultset Will Be Closed On A Commit Or Rollback?

Answer»

USE the DatabaseMetaData METHODS supportsOpen StatementsAcrossCommit() and SUPPORTS Open STATEMENTS Across ROLLBACK().

Use the DatabaseMetaData methods supportsOpen StatementsAcrossCommit() and supports Open Statements Across Rollback().

168.

How Do I Get Runtime Information About The Jdbc Driver?

Answer»

USE the FOLLOWING DATABASEMETADATA METHODS:

getDriverMajorVersion()
getDriverMinorVersion()
getDriverName()
getDriverVersion()

Use the following DatabaseMetaData methods:

169.

How Can I Connect To An Oracle Database Not On The Web Server From An Untrusted Applet?

Answer»

You can use the thin ORACLE JDBC driver in an applet (with some extra PARAMETERS on the JDBC URL). Then, if you have NET8, you can use the connection manager of NET8 on the WEB server to proxy the connection REQUEST to the DATABASE server.

You can use the thin ORACLE JDBC driver in an applet (with some extra parameters on the JDBC URL). Then, if you have NET8, you can use the connection manager of NET8 on the web server to proxy the connection request to the database server.

170.

How Can I Insert Multiple Rows Into A Database In A Single Transaction?

Answer»

Answer : //turn off the IMPLICIT commit
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();

a new transaction is implicitly started. JDBC 2.0 provides a set of methods for EXECUTING a BATCH of database commands. Specifically, the java. sql. Statement interface provides three methods: addBatch(), clearBatch() and executeBatch(). Their documentation is pretty straight forward. The implementation of these methods is optional, so be SURE that your driver supports these.

 

a new transaction is implicitly started. JDBC 2.0 provides a set of methods for executing a batch of database commands. Specifically, the java. sql. Statement interface provides three methods: addBatch(), clearBatch() and executeBatch(). Their documentation is pretty straight forward. The implementation of these methods is optional, so be sure that your driver supports these.

 

171.

How Can I Convert A Java Array To A Java.sql.array?

Answer»

A Java array is a first CLASS object and all of the references basically USE PreparedStatement.setObject() or ResultSet.updateObject() methods for putting the array to an ARRAY in the database. Here's a basic EXAMPLE:

String[] as = { "One", "Two", "Three" };
...
PreparedStatement ps = con.prepareStatement(
"UPDATE MYTABLE SET ArrayNums = ? WHERE MyKey = ?" );
...
ps.setObject( 1, as );

A Java array is a first class object and all of the references basically use PreparedStatement.setObject() or ResultSet.updateObject() methods for putting the array to an ARRAY in the database. Here's a basic example:

172.

What Is The Difference Between Client And Server Database Cursors?

Answer»

What you SEE on the CLIENT side is the current ROW of the cursor which CALLED a Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the server side.

What you see on the client side is the current row of the cursor which called a Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the server side.

173.

How Can Resultset Records Be Restricted To Certain Rows?

Answer»

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.

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,

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.

174.

How Do I Insert An Image File (or Other Raw Data) Into A Database?

Answer»

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.

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,

175.

How Can I Connect From An Applet To A Database On The Server?

Answer»

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.

There are two ways of connecting to a database on the server side.

176.

Can I Use The Jdbc-odbc Bridge Driver In An Applet?

Answer»

No.

No.

177.

What Does Resultset Actually Contain? Is It The Actual Data Of The Result Or Some Links To Databases? If It Is The Actual Data Then Why Can't We Access It After Connection Is Closed?

Answer»

A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns. For example with the Odbc BRIDGE what the underlying implementation layer contains is an ODBC result set. A Type 4 driver EXECUTING a stored procedure that returns a cursor - on an ORACLE database it actually returns a cursor in the databse. The oracle cursor can however be processed LIKE a ResultSet would be from the client. Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.

A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns. For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an oracle database it actually returns a cursor in the databse. The oracle cursor can however be processed like a ResultSet would be from the client. Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.

178.

How Do I Extract The Sql Statements Required To Move All Tables And Views From An Existing Database To Another Database?

Answer»

The operation is performed in 9 steps:

  1. Open a connection to the SOURCE database. Use the DriverManager class.
  2. Find the entire physical layout of the current database. Use the DatabaseMetaData interface.
  3. Create DDL SQL statements for re-creating the current database STRUCTURE. Use the DatabaseMetaData interface.
  4. Build a dependency tree, to determine the order in which tables must be setup. Use the DatabaseMetaData interface.
  5. Open a connection to the target database. Use the DriverManager class.
  6. Execute all DDL SQL statements from (3) in the order given by (4) in the target database to setup the table and VIEW structure. Use the PREPAREDSTATEMENT interface.
  7. If (6) threw exceptions, abort the entire process.
  8. Loop over all tables in the physical structure to generate DML SQL statements for re-creating the data inside the table. Use the ResultSetMetaData interface.
  9. Execute all DML SQL statements from (8) in the target database.

The operation is performed in 9 steps:

179.

What Is The Advantage Of Using A Preparedstatement?

Answer»

For SQL statements that are executed REPEATEDLY, using a PreparedStatement object would almost always be faster than using a Statement object. This is because CREATING a PreparedStatement object by explicitly giving the SQL statement CAUSES the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.

Typically, PreparedStatement OBJECTS are USED for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters.

For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.

Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters.

180.

How Does The Java Database Connectivity (jdbc) Work?

Answer»

The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible CLASSES used in the Java/database communication are placed in PACKAGE java.sql.

Main JDBC classes:

  • DriverManager: Manages a LIST of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under jdbc (such as odbc or dbAnywhere/dbaw) will be used to establish a database Connection.
  • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it EXPLICITLY.
  • Connection: Interface with all methods for contacting a database.
  • Statement: Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
  • RESULTSET: The answer/result from a statement. A ResultSet is a fancy 2D list which encapsulates all outgoing results from a given SQL query.

The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible classes used in the Java/database communication are placed in package java.sql.

Main JDBC classes:

181.

What Is Metadata And Why Should I Use It?

Answer»

METADATA ('data about data') is information about one of two things:

  1. Database information (java.sql.DatabaseMetaData), or
  2. Information about a specific ResultSet (java.sql. ResultSet MetaData).

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.

Metadata ('data about data') is information about one of two things:

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.

182.

How Do I Create A Database Connection?

Answer»

The database connection is created in 3 steps:

  1. Find a proper database 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:

  • CREATE a properly formatted JDBR URL for your database. A JDBC URL has the form jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
  • TRY {
Class.forName("my.database.driver");
}
catch(Exception ex)
{
System.err.println("Could not load database driver: " + ex);
}
  • Connection conn = DriverManager.getConnection("a.JDBC.URL", "databaseLogin", "databasePassword");

The database connection is created in 3 steps:

In java code, the steps are realized in code as follows:

183.

How Can I Send User Authentication Information While Makingurlconnection?

Answer»

You’ll WANT to USE HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

184.

How Do I Find Whether A Parameter Exists In The Request Object?

Answer»

ANSWER : BOOLEAN hasFoo = !(request.getParameter("FOO") == null
|| request.getParameter("foo").EQUALS(""));
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in SERVLET 2.3+)

185.

What Is The Fastest Type Of Jdbc Driver?

Answer»

JDBC driver PERFORMANCE will depend on a number of issues:

  • the quality of the driver code,
  • the size of the driver code,
  • the database SERVER and its load,
  • network topology,
  • 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).

JDBC driver performance will depend on a number of issues:

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).

186.

Why Is Xml Such An Important Development?

Answer»

It removes two constraints which were holding back Web DEVELOPMENTS: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible DEVELOPMENT of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file FORMAT for the storage and transmission of text and data both on and off the Web; and it removes the more COMPLEX options of SGML, making it easier to program for.

It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

187.

I Made My Class Cloneable But I Still Get Can't Access Protected Method Clone. Why?

Answer»

Some of the Java books imply that all you have to do in ORDER to have your class support clone() is IMPLEMENT the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it STANDS, you have to implement your own PUBLIC clone() method, EVEN if it doesn’t do anything special and just calls super.clone().

Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().

188.

How Do I Mix Jsp And Ssi #include?

Answer»

If you’re just including raw HTML, use the #include directive as usual INSIDE your .jsp FILE.

If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.

189.

How Do You Delete A Cookie Within A Jsp?

Answer»

Answer : COOKIE mycook = NEW Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);

190.

How Does Jsp Handle Runtime Exceptions?

Answer»

Using errorPage attribute of page DIRECTIVE and also we need to specify isErrorPage=true if the current page is INTENDED to URL REDIRECTING of a JSP.

Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

191.

What Is The Difference Between Requestdispatcher And Sendredirect?

Answer»

REQUESTDISPATCHER: server-side REDIRECT with request and response objects.

SENDREDIRECT : Client-side redirect with NEW request and response objects.

RequestDispatcher: server-side redirect with request and response objects.

sendRedirect : Client-side redirect with new request and response objects.

192.

What Is The Difference Between Directive Include And Jsp Include?

Answer»

&LT;%@ include>: Used to include STATIC RESOURCES during translation TIME.

JSP include: Used to include DYNAMIC content or static content during runtime.

<%@ include>: Used to include static resources during translation time.

JSP include: Used to include dynamic content or static content during runtime.

193.

How To Pass Information From Jsp To Included Jsp?

Answer»

Using &LT;%jsp:param&GT; tag.

Using <%jsp:param> tag.

194.

What Is The Difference Between Servletcontext And Pagecontext?

Answer»

SERVLETCONTEXT: GIVES the INFORMATION about the container.
PAGECONTEXT: Gives the information about the Request.

ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.

195.

Can We Implement An Interface In A Jsp?

Answer»

No

No

196.

How Many Types Of Jdbc Drivers Are Present And What Are They?

Answer»

There are 4 TYPES of JDBC DRIVERS

  • JDBC-ODBC Bridge Driver
  • Native API Partly JAVA Driver
  • Network protocol Driver
  • JDBC Net pure Java Driver

There are 4 types of JDBC Drivers

197.

What Is New In Jdbc 2.0?

Answer»

With the JDBC 2.0 API, you will be ABLE to do the following:
Scroll forward and backward in a RESULT set or move to a specific row (TYPE_SCROLL_ SENSITIVE, PREVIOUS(), last(), absolute(), relative(), etc.) Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.) SEND multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch()) Use the new SQL3 datatypes as column values like Blob, Clob, Array, STRUCT, Ref.

With the JDBC 2.0 API, you will be able to do the following:
Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_ SENSITIVE, previous(), last(), absolute(), relative(), etc.) Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.) Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch()) Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

198.

How Do I Start Debugging Problems Related To The Jdbc Api?

Answer»

A good WAY to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC TRACE contains a detailed listing of the activity occurring in the system that is related to JDBC operations.

If you use the DriverManager facility to establish your database connection, you use the DriverManager. setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to GET a connection, you use the DataSource.setLogWriter method to enable tracing. (For POOLED connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.

If you use the DriverManager facility to establish your database connection, you use the DriverManager. setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

199.

Can The Jdbc-odbc Bridge Be Used With Applets?

Answer»

Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't ALLOWED. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.

Finally, we WOULD like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in APPLETVIEWER since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a SECURE intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to AVOID security problems.

Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.

Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.

200.

Does The Jdbc-odbc Bridge Support The New Features In The Jdbc 3.0 Api?

Answer»

The JDBC-ODBC BRIDGE provides a LIMITED subset of the JDBC 3.0 API.

The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.