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.

101.

Is The Jdbc-odbc Bridge Multi-threaded?

Answer»

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 calls that it makes to ODBC. Multi-threaded JAVA programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks HELD in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make THINGS simple for FOLKS writing Java programs that use a single-threaded ODBC driver.

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 calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.

102.

Why Can't I Invoke The Resultset Methods Afterlast And Beforefirst When The Method Next Works?

Answer»

You are probably using a DRIVER implemented for the JDBC 1.0 API. You NEED to upgrade to a JDBC 2.0 driver that implements scrollable RESULT sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.

You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.

103.

How Can I Retrieve A String Or Other Object Type Without Creating A New Object Each Time?

Answer»

Creating and garbage collecting potentially large numbers of objects (millions) UNNECESSARILY can really hurt performance. It MAY be better to PROVIDE a way to retrieve data like strings using the JDBC API without always allocating a NEW object. We are studying this issue to SEE if it is an area in which the JDBC API should be improved.

Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object. We are studying this issue to see if it is an area in which the JDBC API should be improved.

104.

What Is The Query Used To Display All Tables Names In Sql Server (query Analyzer)?

Answer»

SELECT * from information_schema.tables.

select * from information_schema.tables.

105.

There Is A Method Getcolumncount In The Jdbc Api. Is There A Similar Method To Find The Number Of Rows In A Result Set?

Answer»

No, but it is easy to find the number of rows. If you are using a scrollable RESULT set, rs, you can CALL the METHODS rs.last and then rs.getRow to find out how MANY rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.

No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.

106.

I Would Like To Download The Jdbc-odbc Bridge For The Java 2 Sdk, Standard Edition (formerly Jdk 1.2). I'm A Beginner With The Jdbc Api, And I Would Like To Start With The Bridge. How Do I Do It?

Answer»

The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no NEED to DOWNLOAD it separately.

The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.

107.

If I Use The Jdbc Api, Do I Have To Use Odbc Underneath?

Answer»

No, this is just one of MANY possible SOLUTIONS. We recommend using a PURE Java JDBC technology-enabled DRIVER, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.

No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.

108.

Once I Have The Java 2 Sdk, Standard Edition, From Sun, What Else Do I Need To Connect To A Database?

Answer»

You still NEED to GET and INSTALL a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity SET up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.

You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.

109.

Where Can I Find Info, Frameworks And Example Source For Writing A Jdbc Driver?

Answer»

There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least ONE free FRAMEWORK, the jxDBCon-Open Source JDBC DRIVER framework. Any driver writer should ALSO review For Driver Writers.

There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open Source JDBC driver framework. Any driver writer should also review For Driver Writers.

110.

How Can I Create A Custom Rowsetmetadata Object From Scratch?

Answer»

ONE unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most COMMONLY available and offers the sun.jdbc.rowset .RowSetMetaDataImpl CLASS. After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to SET the Column Count for a row and the Column Types for each column in the row. For a WORKING code example that includes a custom RowSet MetaData.

One unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most commonly available and offers the sun.jdbc.rowset .RowSetMetaDataImpl class. After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to set the Column Count for a row and the Column Types for each column in the row. For a working code example that includes a custom RowSet MetaData.

111.

How Does A Custom Rowsetreader Get Called From A Cachedrowset?

Answer»

The Reader must be REGISTERED with the CACHEDROWSET using Cached RowSet .setReader javax.sql. RowSet Reader reader). Once that is DONE, a call to Cached RowSet. execute() will, among other things, invoke the readData method.

The Reader must be registered with the CachedRowSet using Cached RowSet .setReader javax.sql. RowSet Reader reader). Once that is done, a call to Cached RowSet. execute() will, among other things, invoke the readData method.

112.

How Do I Implement A Rowsetreader? I Want To Populate A Cachedrowset Myself And The Documents Specify That A Rowsetreader Should Be Used. The Single Method Accepts A Rowsetinternal Caller And Returns Void. What Can I Do In The Readdata Method?

Answer»

"It can be implemented in a wide variety of WAYS..." and is PRETTY vague about what can actually be done. In GENERAL, readData() would obtain or create the data to be loaded, then USE CachedRowSet methods to do the actual loading. This would usually mean inserting rows, so the code would move to the insert ROW, set the column data and insert rows. Then the cursor must be set to to the appropriate position.

"It can be implemented in a wide variety of ways..." and is pretty vague about what can actually be done. In general, readData() would obtain or create the data to be loaded, then use CachedRowSet methods to do the actual loading. This would usually mean inserting rows, so the code would move to the insert row, set the column data and insert rows. Then the cursor must be set to to the appropriate position.

113.

Can I Set Up A Connection Pool With Multiple User Ids? The Single Id We Are Forced To Use Causes Problems When Debugging The Dbms.

Answer»

Since the Connection interface ( and the UNDERLYING DBMS ) REQUIRES a specific user and password, there's not much of a WAY around this in a POOL. While you could create a different Connection for each user, most of the rationale for a pool would then be gone. Debugging is only one of several issues that arise when USING pools.
However, for debugging, at least a couple of other methods come to mind. One is to log executed statements and times, which should allow you to backtrack to the user. Another method that also maintains a trail of modifications is to include user and timestamp as standard columns in your tables. In this last case, you would collect a separate user value in your program.

Since the Connection interface ( and the underlying DBMS ) requires a specific user and password, there's not much of a way around this in a pool. While you could create a different Connection for each user, most of the rationale for a pool would then be gone. Debugging is only one of several issues that arise when using pools.
However, for debugging, at least a couple of other methods come to mind. One is to log executed statements and times, which should allow you to backtrack to the user. Another method that also maintains a trail of modifications is to include user and timestamp as standard columns in your tables. In this last case, you would collect a separate user value in your program.

114.

Detecting Duplicate Keys I Have A Program That Inserts Rows In A Table. My Table Has A Column 'name' That Has A Unique Constraint. If The User Attempts To Insert A Duplicate Name Into The Table, I Want To Display An Error Message By Processing The Error Code From The Database. How Can I Capture This Error Code In A Java Program?

Answer»

A solution that is perfectly portable to all databases, is to execute a query for checking if that UNIQUE value is present before inserting the row. The big advantage is that you can handle your error message in a very SIMPLE way, and the obvious DOWNSIDE is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

You can also get this information in a portable way, and potentially avoid ANOTHER database access, by capturing SQLState messages. Some databases get more SPECIFIC than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.

A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.

115.

What Driver Should I Use For Scalable Oracle Jdbc Applications?

Answer»

Sun recommends USING the thin ( TYPE 4 ) driver.

  • On single processor machines to avoid JNI overhead.
  • On MULTIPLE processor machines, especially running Solaris, to avoid SYNCHRONIZATION bottlenecks.

Sun recommends using the thin ( type 4 ) driver.

116.

Is Possible To Open A Connection To A Database With Exclusive Mode With Jdbc?

Answer»

I think you mean "lock a table in exclusive mode". You cannot OPEN a connection with exclusive mode. Depending on your database engine, you can lock tables or rows in exclusive mode.

In Oracle you would create a statement ST and run
st.execute("lock table mytable in exclusive mode");

Then when you are finished with the table, execute the commit to unlock the table. MYSQL, Informix and SQLServer all have a slightly different syntax for this function, so you'll have to change it depending on your database. But they can all be DONE with execute().

I think you mean "lock a table in exclusive mode". You cannot open a connection with exclusive mode. Depending on your database engine, you can lock tables or rows in exclusive mode.

In Oracle you would create a statement st and run
st.execute("lock table mytable in exclusive mode");

Then when you are finished with the table, execute the commit to unlock the table. Mysql, Informix and SQLServer all have a slightly different syntax for this function, so you'll have to change it depending on your database. But they can all be done with execute().

117.

Update Fails Without Blank Padding. Although A Particular Row Is Present In The Database For A Given Key, Executeupdate() Shows 0 Rows Updated And, In Fact, The Table Is Not Updated. If I Pad The Key With Spaces For The Column Length (e.g. If The Key Column Is 20 Characters Long, And Key Is Msgid, Length 6, I Pad It With 14 Spaces), The Update Then Works!!! Is There Any Solution To This Problem Without Padding?

Answer»

In the SQL standard, CHAR is a fixed length DATA type. In many DBMSes ( but not all), that MEANS that for a WHERE clause to match, EVERY character must match, including size and trailing blanks. As Alessandro indicates, DEFINING CHAR columns to be VARCHAR is the most general answer.

In the SQL standard, CHAR is a fixed length data type. In many DBMSes ( but not all), that means that for a WHERE clause to match, every character must match, including size and trailing blanks. As Alessandro indicates, defining CHAR columns to be VARCHAR is the most general answer.

118.

What Isolation Level Is Used By The Dbms When Inserting, Updating And Selecting Rows From A Database?

Answer»

The answer depends on both your CODE and the DBMS. If the program does not explicitly SET the isolation level, the DBMS default is used. You can determine the default USING Database MetaData. getDefault TransactionIsolation() and the level for the CURRENT Connection with Connection.getTransactionIsolation(). If the default is not appropriate for your transaction, CHANGE it with Connection.setTransactionIsolation(int level).

The answer depends on both your code and the DBMS. If the program does not explicitly set the isolation level, the DBMS default is used. You can determine the default using Database MetaData. getDefault TransactionIsolation() and the level for the current Connection with Connection.getTransactionIsolation(). If the default is not appropriate for your transaction, change it with Connection.setTransactionIsolation(int level).

119.

How Can I Determine The Isolation Levels Supported By My Dbms?

Answer»

USE DatabaseMetaData.supportsTransactionIsolationLevel(INT LEVEL).

Use DatabaseMetaData.supportsTransactionIsolationLevel(int level).

120.

Connecting To A Database Through The Proxy I Want To Connect To Remote Database Using A Program That Is Running In The Local Network Behind The Proxy. Is That Possible?

Answer»

I assume that your PROXY is SET to accept http requests only on port 80. If you want to have a local class behind the proxy connect to the database for you, then you need a servlet/JSP to receive an HTTP request and use the local class to connect to the database and send the response back to the CLIENT.

You could also use RMI where your remote computer class that connects to the database acts as a remote server that talks RMI with the clients. if you implement this, then you will need to tunnel RMI through HTTP which is not that hard.

In SUMMARY, either have a servlet/JSP take HTTP requests, instantiate a class that handles database connections and send HTTP response back to the client or have the local class deployed as RMI server and send requests to it using RMI.

I assume that your proxy is set to accept http requests only on port 80. If you want to have a local class behind the proxy connect to the database for you, then you need a servlet/JSP to receive an HTTP request and use the local class to connect to the database and send the response back to the client.

You could also use RMI where your remote computer class that connects to the database acts as a remote server that talks RMI with the clients. if you implement this, then you will need to tunnel RMI through HTTP which is not that hard.

In summary, either have a servlet/JSP take HTTP requests, instantiate a class that handles database connections and send HTTP response back to the client or have the local class deployed as RMI server and send requests to it using RMI.

121.

How Do I Receive A Resultset From A Stored Procedure?

Answer»

STORED procedures can RETURN a result PARAMETER, which can be a result SET. For a discussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUT parameters, SEE Stored Procedures.

Stored procedures can return a result parameter, which can be a result set. For a discussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUT parameters, see Stored Procedures.

122.

How Can I Write To The Log Used By Drivermanager And Jdbc Drivers?

Answer»

The simplest method is to use DriverManager.println(STRING MESSAGE), which will WRITE to the CURRENT log.

The simplest method is to use DriverManager.println(String message), which will write to the current log.

123.

How Can I Get Or Redirect The Log Used By Drivermanager And Jdbc Drivers?

Answer»

As of JDBC 2.0, use DriverManager.getLogWriter() and DriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManager METHODS getLogStream() and setLogStream(PrintStream out) were USED. These are now DEPRECATED.

As of JDBC 2.0, use DriverManager.getLogWriter() and DriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManager methods getLogStream() and setLogStream(PrintStream out) were used. These are now deprecated.

124.

What Does It Mean To "materialize" Data?

Answer»

This term generally refers to Array, Blob and Clob DATA which is referred to in the database via SQL locators "MATERIALIZING" the data means to RETURN the actual data pointed to by the Locator.

  • For Arrays, use the various forms of getArray() and getResultSet().
  • For Blobs, use getBinaryStream() or getBytes(LONG pos, int length).
  • For Clobs, use getAsciiStream() or getCharacterStream().

This term generally refers to Array, Blob and Clob data which is referred to in the database via SQL locators "Materializing" the data means to return the actual data pointed to by the Locator.

125.

Why Do I Have To Reaccess The Database For Array, Blob, And Clob Data?

Answer»

Most DBMS vendors have implemented these types via the SQL3 Locator type
Some rationales for using Locators RATHER than directly returning the DATA can be seen most clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data. It could be anything; the DBMS has no knowledge of what the data represents. Notice that this effectively demolishes data independence, because applications must now be aware of what the Blob data actually represents. Let's assume an employee table that includes employee images as Blobs.

Say we have an inquiry program that presents multiple employees with department and identification information. To see all of the data for a specific employee, including the image, the SUMMARY row is selected and another screen appears. It is only at this pont that the application needs the specific image. It would be very wasteful and time consuming to bring down an entire employee page of images when only a few would ever be selected in a given run.

Now assume a general interactive SQL application. A query is issued against the employee table. Because the image is a Blob, the application has no idea what to do with the data, so why bring it down, killing performance along the way, in a LONG running operation? Clearly this is not helpful in those applications that need the data everytime, but these and other CONSIDERATIONS have made the most general sense to DBMS vendors.

Most DBMS vendors have implemented these types via the SQL3 Locator type
Some rationales for using Locators rather than directly returning the data can be seen most clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data. It could be anything; the DBMS has no knowledge of what the data represents. Notice that this effectively demolishes data independence, because applications must now be aware of what the Blob data actually represents. Let's assume an employee table that includes employee images as Blobs.

Say we have an inquiry program that presents multiple employees with department and identification information. To see all of the data for a specific employee, including the image, the summary row is selected and another screen appears. It is only at this pont that the application needs the specific image. It would be very wasteful and time consuming to bring down an entire employee page of images when only a few would ever be selected in a given run.

Now assume a general interactive SQL application. A query is issued against the employee table. Because the image is a Blob, the application has no idea what to do with the data, so why bring it down, killing performance along the way, in a long running operation? Clearly this is not helpful in those applications that need the data everytime, but these and other considerations have made the most general sense to DBMS vendors.

126.

What Is An Sql Locator?

Answer»

A LOCATOR is an SQL3 data type that acts as a logical pointer to data that resides on a database server. Read "logical pointer" here as an identifier the DBMS can use to locate and manipulate the data. A Locator allows some MANIPULATION of the data on the server. While the JDBC specification does not directly address Locators, JDBC drivers typically use Locators under the covers to handle Array, Blob, and CLOB data TYPES.

A Locator is an SQL3 data type that acts as a logical pointer to data that resides on a database server. Read "logical pointer" here as an identifier the DBMS can use to locate and manipulate the data. A Locator allows some manipulation of the data on the server. While the JDBC specification does not directly address Locators, JDBC drivers typically use Locators under the covers to handle Array, Blob, and Clob data types.

127.

What Is The Jdbc Syntax For Using A Literal Or Variable In A Standard Statement?

Answer»

First, it should be pointed out that PreparedStatement handles MANY issues for the developer and normally should be preferred over a standard Statement.
Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often affects newbies ( and OTHERS ) is that SQL, like many languages, requires quotes around CHARACTER ( read "String" for Java ) values to DISTINGUISH from numerics. So the clause:
"WHERE myCol = " + myVal
is perfectly valid and works for numerics, but will fail when myVal is a String. Instead use:
"WHERE myCol = '" + myVal + "'"
if myVal equals "stringValue", the clause works out to:
WHERE myCol = 'stringValue'
You can still encounter PROBLEMS when quotes are embedded in the value, which, again, a PreparedStatement will handle for you.

First, it should be pointed out that PreparedStatement handles many issues for the developer and normally should be preferred over a standard Statement.
Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often affects newbies ( and others ) is that SQL, like many languages, requires quotes around character ( read "String" for Java ) values to distinguish from numerics. So the clause:
"WHERE myCol = " + myVal
is perfectly valid and works for numerics, but will fail when myVal is a String. Instead use:
"WHERE myCol = '" + myVal + "'"
if myVal equals "stringValue", the clause works out to:
WHERE myCol = 'stringValue'
You can still encounter problems when quotes are embedded in the value, which, again, a PreparedStatement will handle for you.

128.

How Do I Check In My Code Whether A Maximum Limit Of Database Connections Have Been Reached?

Answer»

Use DatabaseMetaData.getMaxConnections() and COMPARE to the number of CONNECTIONS currently open. Note that a return value of ZERO can mean unlimited or, unfortunately, unknown. Of COURSE, DRIVER Manager .getConnection () will throw an exception if a Connection can not be obtained.

Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited or, unfortunately, unknown. Of course, driver Manager .getConnection () will throw an exception if a Connection can not be obtained.

129.

Why Do I Get Unsatisfiedlinkerror When I Try To Use My Jdbc Driver?

Answer»

The first thing is to be sure that this does not occur when running non-JDBC apps. If so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then it's time to check the documentation that came with the DRIVER or the driver/DBMS SUPPORT. JDBC driver types 1 through 3 have some native code ASPECT and typically require some sort of client install. Along with the install, various environment variables and path or classpath settings must be in place. Because the requirements and installation procedures vary with the provider, there is no reasonable way to provide DETAILS here. A type 4 driver, on the other hand, is pure Java and should never exhibit this problem. The trade off is that a type 4 driver is USUALLY slower.

The first thing is to be sure that this does not occur when running non-JDBC apps. If so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then it's time to check the documentation that came with the driver or the driver/DBMS support. JDBC driver types 1 through 3 have some native code aspect and typically require some sort of client install. Along with the install, various environment variables and path or classpath settings must be in place. Because the requirements and installation procedures vary with the provider, there is no reasonable way to provide details here. A type 4 driver, on the other hand, is pure Java and should never exhibit this problem. The trade off is that a type 4 driver is usually slower.

130.

Db2 Universal Claims To Support Jdbc 2.0, But I Can Only Get Jdbc 1.0 Functionality. What Can I Do?

Answer»

DB2 UNIVERSAL defaults to the 1.0 DRIVER. You have to RUN a special program to enable the 2.0 driver and JDK support. 

DB2 Universal defaults to the 1.0 driver. You have to run a special program to enable the 2.0 driver and JDK support. 

131.

How Do I Disallow Null Values In A Table?

Answer»

NULL capability is a column integrity constraint, normally applied at table creation time. Note that some databases won't ALLOW the constraint to be applied after table creation. Most databases allow a default value for the column as well. The following SQL statement displays the NOT NULL constraint:

CREATE TABLE CoffeeTable (
Type VARCHAR(25) NOT NULL,
Pounds INTEGER NOT NULL,
PRICE NUMERIC(5, 2) NOT NULL
)

Null capability is a column integrity constraint, normally applied at table creation time. Note that some databases won't allow the constraint to be applied after table creation. Most databases allow a default value for the column as well. The following SQL statement displays the NOT NULL constraint:

132.

How Do I Insert/update Records With Some Of The Columns Having Null Value?

Answer»

Use either of the following PreparedStatement methods:

public void setNull(int parameterIndex, int sqlType) throws SQLEXCEPTION
public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException

These methods assume that the columns are NULLABLE. In this case, you can also just omit the columns in an INSERT STATEMENT; they will be automatically assigned null VALUES.

 

Use either of the following PreparedStatement methods:

These methods assume that the columns are nullable. In this case, you can also just omit the columns in an INSERT statement; they will be automatically assigned null values.

 

133.

Is There A Way To Find The Primary Key(s) For An Access Database Table? Sun's Jdbc-odbc Driver Does Not Implement The Getprimarykeys() Method For The Databasemetadata Objects?

Answer»

Answer : // Use meta.getIndexInfo() will
//GET you the PK INDEX. Once
// you know the index, retrieve its column name
DatabaseMetaData meta = con.getMetaData();
String key_colname = NULL;
// get the PRIMARY key information
rset = meta.getIndexInfo(null,null, table_name, TRUE,true);
while( rset.next())
{
String idx = rset.getString(6);
if( idx != null)
{
//Note: index "PrimaryKey" is Access DB specific
// other db server has diff. index syntax.
if( idx.equalsIgnoreCase("PrimaryKey"))
{
key_colname = rset.getString(9);
setPrimaryKey( key_colname );
}
}
}

134.

Why Can't Tomcat Find My Oracle Jdbc Drivers In Classes111.zip?

Answer»

TOMCAT 4.0.1 on NT4 throws the following exception when I try to connect to Oracle DB from JSP.

javax.servlet.ServletException : oracle.jdbc.driver.OracleDriver
java.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriver

But, the Oracle JDBC driver ZIP file (classes111.zip)is available in the system classpath.
COPIED the Oracle Driver class file (classes111.zip) in %TOMCAT_Home - Home%lib DIRECTORY and renamed it to classess111.jar.
Able to connect to Oracle DB from TOMCAT 4.01 VIA Oracle JDBC-Thin Driver.

 

TOMCAT 4.0.1 on NT4 throws the following exception when I try to connect to Oracle DB from JSP.

But, the Oracle JDBC driver ZIP file (classes111.zip)is available in the system classpath.
Copied the Oracle Driver class file (classes111.zip) in %TOMCAT_Home - Home%lib directory and renamed it to classess111.jar.
Able to connect to Oracle DB from TOMCAT 4.01 via Oracle JDBC-Thin Driver.

 

135.

How Does One Get Column Names For Rows Returned In A Resultset?

Answer»

Answer : RESULTSET rs = ...
...
ResultSetMetaData RSMD = rs.getMetaData();
int numCols = rsmd.getColumnCount();
for (int i = 1; i <= numCols; i++)
{
System.out.println("[" + i + "]" +
rsmd.getColumnName(i) + " {" +
rsmd.getColumnTypeName(i) + "}");
}

136.

What Are The Considerations For Deciding On Transaction Boundaries?

Answer»

Transaction processing should always DEAL with more than one statement and a transaction is often described as a Logical Unit of Work ( LUW ). The rationale for transactions is that you want to know definitively that all or none of the LUW completed successfully. Note that this automatically gives you restart capability. Typically, there are two conditions under which you would want to use transactions:

  • Multiple statements involving a single file - An example would be inserting all of a GROUP of rows or all price updates for a given date. You want all of these to take effect at the same time; inserting or changing some SUBSET is not acceptable.
  • Multiple statements involving multiple files - The classic example is transferring money from one account to another or double entry ACCOUNTING; you don't want the debit to succeed and the credit to fail because money or important records will be lost. Another example is a master/detail relationship, where, say, the master contains a total column. If the entire LUW, writing the detail row and updating the master row, is not completed successfully, you A) want to know that the transaction was unsuccessful and B) that a portion of the transaction was not lost or dangling.

Therefore, determining what completes the transaction or LUW should be the deciding factor for transaction boundaries.

Transaction processing should always deal with more than one statement and a transaction is often described as a Logical Unit of Work ( LUW ). The rationale for transactions is that you want to know definitively that all or none of the LUW completed successfully. Note that this automatically gives you restart capability. Typically, there are two conditions under which you would want to use transactions:

Therefore, determining what completes the transaction or LUW should be the deciding factor for transaction boundaries.

137.

How Can I Determine Where A Given Table Is Referenced Via Foreign Keys?

Answer»

DatabaseMetaData.getExportedKeys() returns a RESULTSET with DATA similar to that returned by DATABASE MetaData .getImported Keys(), except that the information relates to other TABLES that reference the given table as a foreign key container.

DatabaseMetaData.getExportedKeys() returns a ResultSet with data similar to that returned by Database MetaData .getImported Keys(), except that the information relates to other tables that reference the given table as a foreign key container.

138.

How Can I Get Information About Foreign Keys Used In A Table?

Answer»

DatabaseMetaData.getImportedKeys() RETURNS a RESULTSET with data about foreign key columns, TABLES, sequence and update and delete rules.

DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key columns, tables, sequence and update and delete rules.

139.

Can I Use Jdbc To Execute Non-standard Features That My Dbms Provides?

Answer»

The answer is a qualified yes. As discussed under SQL Conformance: "One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS DRIVER. This means that an application is free to use as much SQL functionality as desired, but it runs the RISK of receiving an error on some DBMSs. In fact, an application query may be something other than SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example)."

CLEARLY this means either giving up portability or checking the DBMS currently used before invoking specific OPERATIONS.

The answer is a qualified yes. As discussed under SQL Conformance: "One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query may be something other than SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example)."

Clearly this means either giving up portability or checking the DBMS currently used before invoking specific operations.

140.

What Is Dml?

Answer»

DML is an abbreviation for Data Manipulation LANGUAGE. This portion of the SQL standard is concerned with manipulating the data in a database as opposed to the structure of a database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.

DML is an abbreviation for Data Manipulation Language. This portion of the SQL standard is concerned with manipulating the data in a database as opposed to the structure of a database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.

141.

What Is The Significance Of Databasemetadata.tableindexstatistics? How To Obtain And Use It?

Answer»

To ANSWER the second question first, the tableIndexStatistic constant in the TYPE column will identify one of the ROWS in the ResultSet RETURNED when DatabaseMetaData.getIndexInfo() is invoked. If you analyze the WORDY API, a tableIndexStatistic row will CONTAIN the number of rows in the table in the CARDINALITY column and the number of pages used for the table in the PAGES column.

To answer the second question first, the tableIndexStatistic constant in the TYPE column will identify one of the rows in the ResultSet returned when DatabaseMetaData.getIndexInfo() is invoked. If you analyze the wordy API, a tableIndexStatistic row will contain the number of rows in the table in the CARDINALITY column and the number of pages used for the table in the PAGES column.

142.

What Types Of Datasource Objects Are Specified In The Optional Package?

Answer»
  • BASIC - Provides a standard Connection object.
  • Pooled - Provides a Connection pool and returns a Connection that is controlled by the pool.
  • Distributed - Provides a Connection that can participate in distributed transactions ( more than one DBMS is involved). It is anticipated, but not ENFORCED, that a distributed DATASOURCE will also provide pooling.

HOWEVER, there are no standard methods available in the DataSource class to determine if one has obtained a pooled and/or distributed Connection.

However, there are no standard methods available in the DataSource class to determine if one has obtained a pooled and/or distributed Connection.

143.

What Is A Jdbc 2.0 Datasource?

Answer»

The DataSource class was INTRODUCED in the JDBC 2.0 Optional Package as an EASIER, more generic means of obtaining a Connection. The actual driver providing services is DEFINED to the DataSource OUTSIDE the application ( Of course, a production quality app can and should PROVIDE this information outside the app anyway, usually with properties files or ResourceBundles ). The documentation expresses the view that DataSource will replace the common DriverManager method.

The DataSource class was introduced in the JDBC 2.0 Optional Package as an easier, more generic means of obtaining a Connection. The actual driver providing services is defined to the DataSource outside the application ( Of course, a production quality app can and should provide this information outside the app anyway, usually with properties files or ResourceBundles ). The documentation expresses the view that DataSource will replace the common DriverManager method.

144.

Does The Database Server Have To Be Running Java Or Have Java Support In Order For My Remote Jdbc Client App To Access The Database?

Answer»

The answer should always be no. The two critical REQUIREMENTS are LAN/internet connectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, but other communication protocols are possible. Unspoken, but assumed here is that the DBMS has been started to listen on a communications port. It is the JDBC driver's job to convert the SQL statements and JDBC calls to the DBMS' native protocol. From the SERVER's point of view, it's just another data request coming into the port, the programming LANGUAGE used to send the data is IRRELEVANT at that point.

The answer should always be no. The two critical requirements are LAN/internet connectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, but other communication protocols are possible. Unspoken, but assumed here is that the DBMS has been started to listen on a communications port. It is the JDBC driver's job to convert the SQL statements and JDBC calls to the DBMS' native protocol. From the server's point of view, it's just another data request coming into the port, the programming language used to send the data is irrelevant at that point.

145.

Which Java And Java.sql Data Types Map To My Specific Database Types?

Answer»

JDBC is, of necessity, reliant on the DRIVER and underlying DBMS. These do not always adhere to standards as closely as we would like, including differing names for standard Java TYPES. To deal with this, first, there are a number of tables AVAILABLE in the JDK JDBC DOCUMENTATION DEALING with types.

JDBC is, of necessity, reliant on the driver and underlying DBMS. These do not always adhere to standards as closely as we would like, including differing names for standard Java types. To deal with this, first, there are a number of tables available in the JDK JDBC documentation dealing with types.

146.

When An Sql Select Statement Doesn't Return Any Rows, Is An Sqlexception Thrown?

Answer»

No. If you want to throw an exception, you could WRAP your SQL related CODE in a custom class and throw something like ObjectNotFoundException when the RETURNED RESULTSET is EMPTY.

No. If you want to throw an exception, you could wrap your SQL related code in a custom class and throw something like ObjectNotFoundException when the returned ResultSet is empty.

147.

What Is Optimistic Concurrency?

Answer»

An optimistic approach dispenses with locks ( except during the actual update ) and usually involves COMPARISON of timestamps, or GENERATIONS of data to ensure that data hasn't changed between ACCESS and update times. It's generally explained that the term optimistic is used because the expectation is that a clash between MULTIPLE updates to the same data will seldom occur.

An optimistic approach dispenses with locks ( except during the actual update ) and usually involves comparison of timestamps, or generations of data to ensure that data hasn't changed between access and update times. It's generally explained that the term optimistic is used because the expectation is that a clash between multiple updates to the same data will seldom occur.

148.

What Is Pessimistic Concurrency?

Answer»

With a pessimistic approach, locks are used to ensure that no users, other than the one who holds the LOCK, can update data. It's generally explained that the term pessimistic is used because the expectation is that many users will TRY to update the same data, so one is pessimistic that an update will be able to complete properly. Locks may be acquired, depending on the DBMS vendor, AUTOMATICALLY via the selected Isolation LEVEL. Some vendors also implement 'Select... for Update', which explicitly acquires a lock.

With a pessimistic approach, locks are used to ensure that no users, other than the one who holds the lock, can update data. It's generally explained that the term pessimistic is used because the expectation is that many users will try to update the same data, so one is pessimistic that an update will be able to complete properly. Locks may be acquired, depending on the DBMS vendor, automatically via the selected Isolation Level. Some vendors also implement 'Select... for Update', which explicitly acquires a lock.

149.

Can I Get Information About A Resultset's Associated Statement And Connection In A Method Without Having Or Adding Specific Arguments For The Statement And Connection?

Answer»

YES. USE ResultSet.getStatement(). From the RESULTING STATEMENT you can use Statement.getConnection().

Yes. Use ResultSet.getStatement(). From the resulting Statement you can use Statement.getConnection().

150.

How Can I Tell If My Jdbc Driver Normalizes Java.sql.date And Java.sql.time Objects?

Answer»

To actually determine the values, the OBJECTS must be converted to a java.util.Date and examined. See What does normalization mean for java.sql.Date and java.sql.Time? for the definition of normalization. NOTICE that even a debugger will not show whether these objects have been normalized, since the getXXX methods in java.sql.Date for time elements and in java.sql.Time for date elements throw an exception.

So, while a java.sql.Date may show 2001-07-26, it's normalized only if the java.util.Date value is:
Thu Jul 26 00:00:00 EDT 2001

and while a java.sql.Time may show 14:01:00, it's normalized only if the java.util.Date value is:
Thu Jan 01 14:01:00 EST 1970

To actually determine the values, the objects must be converted to a java.util.Date and examined. See What does normalization mean for java.sql.Date and java.sql.Time? for the definition of normalization. Notice that even a debugger will not show whether these objects have been normalized, since the getXXX methods in java.sql.Date for time elements and in java.sql.Time for date elements throw an exception.

So, while a java.sql.Date may show 2001-07-26, it's normalized only if the java.util.Date value is:
Thu Jul 26 00:00:00 EDT 2001

and while a java.sql.Time may show 14:01:00, it's normalized only if the java.util.Date value is:
Thu Jan 01 14:01:00 EST 1970