Top 50 Jdbc Interview Questions You Must Prepare 14.Jun.2024

The OSI-approved CDDL license is being used for project GlassFish which allows developers to view, use, edit, and alter the code, and distribute it or use it in production. Portions of this code are not yet available in source form. Because of this, a few portions are currently also under a Binary Distribution License. As time goes on, we’ll make more of the code available, with the eventual goal of making all the code available, and removing the Binary Distribution license. This isn’t some sort of evil plot – it’s hard work moving stuff out into an Open environment, we expect to have a roadmap for our timing for this published by the end of the Summer.

People who want to redistribute a build of our application server do not have a license to use the CTS nor can they use the Java Compatibility brand. They may choose to sign a JDL commercial license and pass the CTS which would then allow them to distribute the code and use the Java Compatibility brand.

The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

This term generally refers to Array, Blob and Clob data which is referred to in the database via SQL locators "Materializing" the data me 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().

I assume that your proxy is set to accept http requests only on port 8@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.

During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

Also know as IS-95, CDMA One is a 2nd generation wireless technology. Supports speeds from 14.4Kbps to 115K bps.

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

Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.

GlassFish is the name for the open source development project for building a Java EE 5 application server. It is based on the source code for Sun Java System Application Server PE 9 donated by Sun Microsystems and TopLink persistence code donated by Oracle. This project provides a structured process for developing a high quality application server that makes new features available faster than ever before. It is the response to Java developers who want access to the source code and the ability to contribute to the development of Sun’s next generation application server which is based on GlassFish. This project is designed to encourage communication between Sun and Oracle engineers and the community and will enable all developers to participate in the application server development process.

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.

The wer 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 me 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 me either giving up portability or checking the DBMS currently used before invoking specific operations.

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

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>

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.

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.

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

When a thread terminates its processing, it enters the dead state.

GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method.

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
)

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

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

Using System.exit(1); in try block will not allow finally code to execute.

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.

  • A servlet container is a specialized web server that supports servlet execution.
  • It combines the basic functionality of a web server with certain Java/servlet specific optimizations and extensions (such as an integrated Java runtime environment, and the ability to automatically trlate specific URLs into servlet requests).
  • Individual servlets are registered with a servlet container, providing the container with information such as the functionality, the URL used for identification.
  • The servlet container then initializes the servlet as necessary and delivers requests to the servlet as they arrive.
  • Many containers can dynamically add and remove servlets from the system, allowing new servlets to quickly be deployed or removed without affecting other servlets running from the same container.
  • Servlet containers are also referred to as web containers or web engines.

The values are defined in the class java.sql.Connection and are:

  • TRANSACTION_NONE
  • TRANSACTION_READ_COMMITTED
  • TRANSACTION_READ_UNCOMMITTED
  • TRANSACTION_REPEATABLE_READ
  • TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels.

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.

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

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.

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.

Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers.

A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.

A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation.
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data trmitted to a servlet only looking at a request string.

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

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBe, with a standard set of properties and an event notification .

Follow the standard instructions for when the isapi_redirector.dll
Configure IIS to use "integrated windows security".
In server.xml, make sure you disable tomcat authentication.

Use DatabaseMetaData.supportsTractionIsolationLevel(int level).

We can give relative URL when we use ServletRequest and not while using ServletContext.

As you have learned, a Java applet can only connect to the server from which the user downloaded the applet. In addition, some browser, such as Netscape, do not let an applet write or read local files. Therefore, a database applet cannot write search result to a file or insert data into a database. You must take these restrictions into consideration when you design an applet that is going to access a database.

Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers

  • Register a driver
  • Specify a database
  • Open a database connection
  • Submit a query
  • Receive results
  • Process results

There are two types of RowSet are there. They are:

  • Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.
  • Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

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.

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.

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

The following methods have been added to ServletRequest 2.4 version:

  public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

There are 4 types of JDBC Drivers

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

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or Servlet Context.

  1. boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
  2. boolean hasParameter = request.getParameterMap().contains(theParameter); (which works in Servlet 2.3+)