Java Examples - Connect to a Database


Problem Description:

How to connect to a database using JDBC? Assume that database name is testDb and it has table named employee which has 2 records.


Following example uses getConnection, createStatement & executeQuery methods to connect to a database & execute queries.

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) {
      try {
      catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      System.out.println("JDBC Class found");
      int no_of_rows = 0;
      try {
         Connection con = DriverManager.getConnection
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery
         ("SELECT * FROM employee");
         while ( {
         System.out.println("There are "+ no_of_rows 
         + " record in the table");
      catch(SQLException e){
         System.out.println("SQL exception occured" + e);


The above code sample will produce the following result.The result may vary. You will get ClassNotfound exception if your JDBC driver is not installed properly.

JDBC Class found
There are 2 record in the table