JDBC interview question set 2/JDBC Interview Questions and Answers for Freshers & Experienced

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

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.

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

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.

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

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.

How Can I Create A Custom Rowsetmetadata Object From Scratch?

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.

How Does A Custom Rowsetreader Get Called From A Cachedrowset?

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.

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.

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.

What Driver Should I Use For Scalable Oracle Jdbc Applications?

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.

What are the isolation levels of connections in JDBC?

<> The transaction isolation level is a value that decides the level at which inconsistent data is permitted in a transaction, which means it represents the degree of isolation of one transaction from another. A higher level of isolation will result in improvement of data accuracy, but it might decrease the number of concurrent transactions. Similarly, a lower level of isolation permits for more concurrent transactions, but it reduces the data accuracy.

<> To ensure data integrity during transactions in JDBC, the DBMS make use of locks to prevent access to other accesses to the data which is involved in the transaction. Such locks are necessary for preventing Dirty Read, Non-Repeatable Read, and Phantom-Read in the database.

<> It is used for the locking mechanism by DBMS and can be set using setTransactionIsolation() method. You can obtain details about the level of isolation used by the connection using getTransactionIsolation() method.

What is JDBC Transaction Management and why is it needed?

The sequence of actions (SQL statements) served as a single unit that is called a transaction. Transaction Management places an important role in RDBMS-oriented applications to maintain data consistency and integrity.
Transaction Management can be described well – by using ACID properties. ACID stands for Atomicity, Consistency, Isolation, and Durability.
Atomicity - If all queries are successfully executed, then only data will be committed to the database.
Consistency - It ensures bringing the database into a consistent state after any transaction.
Isolation - It ensures that the transaction is isolated from other transactions.
Durability - If a transaction has been committed once, it will remain always committed, even in the situation of errors, power loss, etc.
Need for Transaction Management:
When creating a connection to the database, the auto-commit mode will be selected by default. This implies that every time when the request is executed, it will be committed automatically upon completion.
We might want to commit the transaction after the execution of few more SQL statements. In such a situation, we must set the auto-commit value to False. So that data will not be able to commit before executing all the queries. In case if we get an exception in the transaction, we can rollback() changes made and make it like before.

How Do I Receive A Resultset From A Stored Procedure?

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.

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

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

What Is An Sql Locator?

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.

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

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.

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

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.

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

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

How Do I Disallow Null Values In A Table?

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 (

What Are The Considerations For Deciding On 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:

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.

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

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.

What causes “No suitable driver” error?

“No suitable driver” error occurs during a call to the DriverManager.getConnection() method, because of the following reasons:

1. Unable to load the appropriate JDBC drivers before calling the getConnection() method.
2. It can specify an invalid or wrong JDBC URL, which cannot be recognized by the JDBC driver.
3. This error may occur when one or more shared libraries required by the bridge cannot be loaded.

Explain the usage of the getter and setter methods in ResultSet.

<> Getter methods: These are used for retrieving the particular column values of the table from ResultSet. As a parameter, either the column index value or column name should be passed. Usually, the getter method is represented as getXXX() methods.
int getInt(string Column_Name)
The above statement is used to retrieve the value of the specified column Index and the return type is an int data type.

<> Setter Methods: These methods are used to set the value in the database. It is almost similar to getter methods, but here it requires to pass the data/values for the particular column to insert into the database and the column name or index value of that column. Usually, setter method is represented as setXXX() methods.
void setInt(int Column_Index, int Data_Value)
The above statement is used to insert the value of the specified column Index with an int value

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

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.

What Is Dml?

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.

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

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.

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

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

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?

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.

Which Java And Java.sql Data Types Map To My Specific Database 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.

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

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.

What Is Optimistic Concurrency?

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.

What Is Pessimistic Concurrency?

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.

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

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.

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

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.

What Is Jdo?

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

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

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.

What is JDBC Batch Processing and what are it’s benefits?

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.

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

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.

What Jdbc Objects Generate Sqlwarnings?

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.

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

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.

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

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.

What Does Setfetchsize() Really Do?

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.

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

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

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

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

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?

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.

What Is The Advantage Of Using A Preparedstatement?

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.

What Is The Difference Between Directive Include And Jsp Include?

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

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

Explain the types of RowSet available in JDBC.

A RowSet is an object that encapsulates a set of rows from JDBC result sets or tabular data sources.
There are five types of RowSet interfaces available in JDBC. They are:

<> JDBCRowSet: It is a connected RowSet, which is having a live connection to the database, and all calls on this are percolated to the mapping call in the JDBC connection, result set, or statement. The Oracle implementation of JDBCRowSet is done by using oracle.jdbc.rowset.OracleJDBCRowSet .

<> CachedRowSet: It is a RowSet in which the rows are cached and RowSet is disconnected, which means it does not maintain an active database connection. The oracle.jdbc.rowset.OracleCachedRowSet class is used as the Oracle implementation of CachedRowSet.

<> WebRowSet: It is an extension to CachedRowSet and it represents a set of fetched rows of tabular data that can be passed between tiers and components so that no active data source connections need to be maintained.
It provides support for the production and consumption of result sets and their synchronization with the data source, both in XML(Extensible Markup Language) format and in a disconnected fashion. This permits result sets to be transmitted across tiers and over Internet protocols. The Oracle implementation of WebRowSet is done by using oracle.jdbc.rowset.OracleWebRowSet .

<> FilteredRowSet: It’s an extension to WebRowSet and gives programmatic support to filter its content. This enables you to avoid the difficulty of query supply and processing involved. The Oracle implementation of FilteredRowSet is done by using oracle.jdbc.rowset.OracleFilteredRowSet .

What is the use of setFetchSize() and setMaxRows() methods in Statement?

We can use setMaxRows(int i) method to limit the number of rows that the database returns from the query. You can achieve the same thing using the SQL query itself. For example, in MySQL, we can use the LIMIT clause to set the max rows that will be returned by the query.

Understanding fetchSize can be tricky, for that you should know how Statement and ResultSet works. When we execute a query in the database, the result is obtained and maintained in the database cache and ResultSet is returned. ResultSet is the cursor that has the reference to the result in the database.

Let’s say we have a query that returns 100 rows and we have set fetchSize to 10, so in every database trip JDBC driver will fetch only 10 rows and hence there will be 10 trips to fetch all the rows. Setting optimal fetchSize is helpful when you need a lot of processing time for each row and number of rows in the result is huge.

We can set fetchSize through Statement object but it can be overridden through ResultSet object setFetchSize() method.

Result Set’s index Starts with 0 or 1?

Result Set’s index starts with 1.

Explain JDBC Batch processing.

<> Batch processing is the process of executing multiple SQL statements in one transaction. For example, consider the case of loading data from CSV(Comma-Separated Values) files to relational database tables. Instead of using Statement or PreparedStatement, we can use Batch processing which executes the bulk of queries in a single go for a database.

<> Advantages of Batch processing:
It will reduce the communication time and improves performance.
Batch processing makes it easier to process a huge amount of data and consistency of data is also maintained.
It is much faster than executing a single statement at a time because of the fewer number of database calls.

<> How to perform Batch processing?
To perform Batch processing, addBatch() and executeBatch() methods are used. These 2 methods are available in the Statement and PreparedStatement classes of JDBC API.

What are the types of JDBC statements?

Statements are useful for sending SQL commands to the database and receiving data from the database. There are three types of statements in JDBC. They are:

Statement: It is the factory for ResultSet. It is used for general-purpose access to the database by executing the static SQL query at runtime. Example:
Statement st = conn.createStatement( );
ResultSet rs = st.executeQuery();

PreparedStatement: It is used when we need to give input data to the query at runtime and also if we want to execute SQL statements repeatedly. It is more efficient than a statement because it involves the pre-compilation of SQL. Example:
String SQL = "Update item SET limit = ? WHERE itemType = ?";
PreparedStatement ps = conn.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();

CallableStatement: It is used to call stored procedures on the database. It is capable of accepting runtime parameters. Example:
CallableStatement cs = con.prepareCall("{call SHOW_CUSTOMERS}");
ResultSet rs = cs.executeQuery();

R4R Team
R4R provides JDBC Freshers questions and answers (JDBC Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,JDBC interview question set 2,JDBC Freshers & Experienced Interview Questions and Answers,JDBC Objetive choice questions and answers,JDBC Multiple choice questions and answers,JDBC objective, JDBC questions , JDBC answers,JDBC MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for JDBC fresher interview questions ,JDBC Experienced interview questions,JDBC fresher interview questions and answers ,JDBC Experienced interview questions and answers,tricky JDBC queries for interview pdf,complex JDBC for practice with answers,JDBC for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .