Logo F2FInterview

JDBC Interview Questions

Q   |   QA

To establish a connection you need to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

String url = “jdbc:odbc:Fred”;
Connection con = DriverManager.getConnection(url, “Fernanda”, “J8?);

A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object

Statement stmt = con.createStatement();

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString(”COF_NAME”);

The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.

Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)

The life cycle of a servlet consists of the following phases:

  • DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
  • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
  • Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.
  • Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
  • ResultSet: The ResultSet represents set of rows retrieved due to query execution.

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: