Interview Questions On Java,Java EE

Enter your email address:

Add to Technorati Favorites
Google PageRank Checker
Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Wednesday, October 24, 2007

How do you connect to a MySql Database using JDBC?

Recently some newbie asked me a simple question of connecting to MySql database using JDBC.Here is a code snippet for that.The important thing here is to ensure that you have added MySql database driver classes(mysql.jar) in your classpath. Here goes the code snippet:
import java.sql.*;

public class MySqlConnect {

public static void main (String[] args)
Connection connection = null;

String userName = "root";
String password = "bunty";
String url = "jdbc:mysql://localhost:3306/systdb";

Class.forName ("com.mysql.jdbc.Driver").newInstance ();

connection = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
catch (Exception e)
System.err.println ("Connection to database server cannot be establish");
if (connection != null)
connection.close ();
System.out.println ("Database connection terminated");
catch (Exception e) { System.out.println ("These connection errors can be ignored."); }
Continue reading...

Saturday, June 9, 2007

How to get count of rows there are in a Result Set?

There are three ways:
- Do a query like "select count(*) from ... "
-If you need all the data, count the rows as you loop through the data:

int count = 0;
while ( {
  // anything that you like to do here
-If you have a JDBC 3 driver, you can call rs.afterLast() to move to the end and then rs.getRow() to get the row number. This Result Set MUST have a scrollable cursor. Either ScrollSensitive or Insensitive but it does not  work with a Forward Only cursor
Continue reading...

Is it must to close all my ResultSets, Statements and Connections?

This is absolutely necessary and critical to close all the JDBC resources.When you are using JDBC API you are not only allocating resources on Java side but in a database server as well. Failure to properly close ResultSets, Statements (and PreparedStatements and CallableStatements) and Connections can cause
-Exhaustion of connections that can be opened or used
- No new result sets creation
- No execution of any queries of any kind
- DB server get very slow
- Your program/database server will crash
Continue reading...


TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.

TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

This needs a small coding effort to verify this differntiation.Any volunteers? Please write in your comments to put your understanding about this concept.

Continue reading...

How can a cursor move in scrollable result sets?

JDBC result sets are created with three properties: type, concurrency and holdability.
The type can be one of

The concurrency can be one of

The holdability can be one of

JDBC allows the full cross product of these. Some database like SQL 2003 prohibits the combination {TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE}, but this combination is supported by some vendors, notably Oracle.

The movable cursors,moving forward and backward on a resultset is one of the new features in the JDBC 2.0 API. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

ResultSet resultSet =  stmt.executeQuery("SELECT FNAME, LNAME FROM EMPLOYEE");

while ( {

. . . // iterates forward through resultSet


. . .

resultSet.absolute(5); // moves cursor to the fifth row

. . .

resultSet.relative(-2); // moves cursor to the third row

. . .

resultSet.relative(4); // moves cursor to the seventh row

. . .

resultSet.previous(); // moves cursor to sixth row

. . .

int rowNumber = resultSet.getRow(); // rowNumber should be 6

resultSet.moveAfterLast(); // moves cursor to position // after last row

while (previous()) {

. . . // iterates backward through resultSet


When a resultset type is defined then it is also significant to define whether it is readonly or updatable and type and concurrency should be in the same order as shown in the code above.If you change the order then compiler can not distinguish it.If you specify the constant TYPE_FORWARD_ONLY, it creates a nonscrollable result set, in which the cursor moves forward only. The default value of ResultSet object type is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
Continue reading...

Tuesday, May 22, 2007

How will you differentiate the following two ways of loading a database driver?

(1)DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

In case one, to load the driver, one needs an appropriate class to load, make a driver instance and register it with the JDBC driver manager. Class.forName() will cause the class to create an instance, and call the current class loader's DriverManager.registerDriver() method to announce its presence.While DriverManager.registerDriver registers an instance of the with driver manager.
Continue reading...

What are new features from JDBC2.0 onwards?

New Features in JDBC 2.0:
-Scrollable resultset
-No more updations on tables through queries required,one can use methods provided like updateRow(),insertRow() and deleteRow() etc.
-Send multiple SQLs to database as a unit/batch(addbatch(),executeBatch() )
-Use new SQL3 datatypes as column values like Blob,Clob etc.
Continue reading...

How do you call a stored procedure in Java?

Through a CallableStatement: Callable statements are implemented by the CallableStatement object. A CallableStatement is a way to execute stored procedures in a JDBC-compatible database.
Continue reading...

What is the difference between executeQuery () and executeUpdate()?

The difference between executeQuery and executeUpdate is that executeUpdate is for executing statements that change data in the database. For example, use executeUpdate to execute a CREATE an INSERT or an UPDATE statement. executeUpdate returns an int, and the value of that int corresponds to the number of records that were modified. While executeQuery() method is used for executing SQL statements and it returns ResultSet object.
Continue reading...

What is the difference between executeQuery () and execute() ?

The return type of execute() method is boolean , if true that means a ResultSet object is returned, if false no result is returned.The ResultSet is obtained on Statement object in such case through getResultSet method.In case of executeQuery() method once executed returns ResultSet object.
Continue reading...

What is PreparedStatement and how is different from Statement?

A PreparedStatement, in contrast to a Statement, is used for SQL statements that are executed multiple times with different values. For instance, you might want to insert several values into a table, one after another. The advantage of the PreparedStatement is that it is pre-compiled, reducing the overhead of parsing SQL statements on every execution.
In such cases DBMS will execute the query directly without worrying about compiling the statement again.
Continue reading...

What are the different types of Statements?

There are several statements supported in JDBC and mainly they are as given below:
-Regular statement (use createStatement method),
-Prepared statement (use prepareStatement method)
-Callable statement (use prepareCall)
Continue reading...

How do you establish database connection using JDBC?

The database connection using JDBC involves two steps:
- Loading database driver class
- Making the connection to database
Here is code snippet for connection to the database:

String driverClassName="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:dsnname";
String usrname="hello";
String passwd="india";
String qry="select username from users";
Class.forName(driverClassName);//loading the database driver
Connection con=DriverManager.getConnection(url,usrname,passwd);
Statement stmt=con.createStatement();
ResultSet rs =stmt.executeQuery(qry);

} catch(Exception exc){

Continue reading...

What are four drivers available in JDBC?

Type 1: JDBC-ODBC bridge.It is for databases that support ODBC.It Uses a bridging technology to access the database (e.g., Sun's JDBC-ODBC Bridge driver)

Type 2: JDBC to a database vendor DLL.It uses native API drivers.It requires software on the client machine. Uses native API drivers; requires software on the client machine Supplied by the vendor or by third parties.

Type 3: JDBC to middleware software to the database.It translates JDBC calls into a database-independent network protocol, which a server then translates into a database protocol

Type 4: Pure Java to a network protocol.It uses the network protocols built into the database engine

Type1 and Type2 database drivers are not suitable for Internet based connection to the databases as these types of database drivers are to be installed on client machine.
Continue reading...

What is JDBC ?

JDBC is Java Database Connectivity, a collection of APIs for connecting a Java application to a database. It is an abstraction over ODBC so as to provide Java clients an interface to connect to the database end.The latest update of the JDBC API is JDBC3.0. It contains many features, including scrollable result sets and the SQL:1999 data types.
The first version of JDBC(JDBC1.22 with JDK1.1.x release) had only one pacakge named java.sql.* but in JDBC2.0(released with Java2) there had been introduced several new features in two pacakges namely,java.sql.* and javax.sql.*
Continue reading...

Wednesday, May 2, 2007

Questions on Java Database Connectivity

Continue reading...

Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker