Add

Java Language - Connect to a Database

 

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

Solution

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 {

         Class.forName("org.apache.derby.jdbc.ClientDriver");

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

            "jdbc:derby://localhost:1527/testDb","username", "password"); 

         Statement stmt = con.createStatement();

         ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");

         while (rs.next()) {

            no_of_rows++;

         }

         System.out.println("There are "+ no_of_rows + " record in the table");

      } catch(SQLException e){

         System.out.println("SQL exception occured" + e);

      }

   }

}

Result

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

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.