Steps to develop JDBC Code

There are basically five steps to connect a Java application with any RDBMS using JDBC. These steps are as follows —

 

Step 1: Load the driver

Loading a database driver is the very first step towards making JDBC connectivity with any RDBMS. It is necessary to load the JDBC drivers before attempting to connect to the database. The JDBC drivers automatically register themselves with the JDBC system when loaded. Since JDBC 4.0, explicitly loading the driver is optional. It just requires putting the vendor’s JAR file in the classpath, and then JDBC driver manager can discover and load the driver automatically.

Here is the code snippet for loading the JDBC driver:

Class.forName(driver).newInstance();
 

Step 2: Establish the Connection

In the above step we have loaded the database driver to be used. Now it’s time to make the connection with the database server. In this step we will logon to the RDBMS with database url, user name and password.

Here is the code snippet for creating the Connection object:

Connection con = DriverManager.getConnection(url, username, password);
 

Step 3: Create the Statement

The createStatement() method of Connection interface is used to create Statement object. The goal of Statement is  to run queries with the RDBMS.

Here is the code snippet that actually creates the Statement object:

Statement st = con.createStatement();
 

Step 4: Execute query to get results

In the previous step we have established the connection with the database, now it’s time to execute query against database. We can run any type of query against database to perform database operations. 

Here is the code snippet that actually executes the statements against database:

ResultSet rs = st.executeQuery("select * from students");

//looping into the ResultSet object
while(rs.next()){ 

System.out.println("Roll: " + rs.getInt(1) + " Name: " + rs.getString(2));
}
 

Step-5: Close the Connection object

Finally it is necessary to disconnect from the RDBMS and release resources being used. Since Java SE7, JDBC can use try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement.

Here is the code snippet for disconnecting the application explicitly from RDBMS:

con.close();

In the next section, we will learn how to write the complete JDBC code using MySQL RDBMS.