Wednesday, 1 October 2014

Load jdbc driver using DriverManager.registerDriver() method

DriverManager class acts as an interface between Java Application and JDBC driver. DriverManager class provides 'registerDriver' method to register given driver with DriverManager.

DriverManager class provides two variants of registerDriver method, to register jdbc driver.
   public static void registerDriver(Driver driver)
   public static void registerDriver(Driver driver, DriverAction da)

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");       
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);
        
        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
 rs.close();
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun
Dropping table employee





Prevoius                                                 Next                                                 Home

Load jdbc driver using forName

java.lang.Class provides 'forName' method to load a class into JVM. A call to forName("X") causes the class named X to be initialized.

There are two variants of forName method available in java.lang.Class.
   public static Class<?> forName(String className)
   public static Class<?> forName(String name,boolean initialize, ClassLoader loader)

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);
        
        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
 rs.close();
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun
Dropping table employee





Prevoius                                                 Next                                                 Home

How to load JDBC Driver

First step in JDBC Application is to load the JDBC driver. JDBC driver is vendor implementation of java.sql.Driver interface. There are many ways to load jdbc driver into the JVM.




Prevoius                                                 Next                                                 Home

Core Classes/Interfaces in sql package

Classes :
java.sql.DriverManager : Responsible to load the jdbc driver classes and to create Connection object.

Interfaces:
java.sql.Connection: Interface represents a database connection. SQL statements are executed and results are returned within the context of a connection.

java.sql.Statement: The object used for executing a static SQL statement and returning the results it produces.

java.sql.PreparedStatement : Represents a precompiled SQL statement.A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

java.sql.CallableStatement : The interface used to execute SQL stored procedures.

java.sql.ResultSet : A table of data representing a database result set, which is usually generated by executing a statement that queries the database.




Prevoius                                                 Next                                                 Home

First JDBC Application

Step 1 : import sql package
             import java.sql.*;

Step 2: Register jdbc driver. By using below statement, we are loading main driver class into the JVM.
       Ex : Class.forName("com.mysql.jdbc.Driver");

Step 3: Open connection to database, using DriverManager class.
      Ex:
      String url = "jdbc:mysql://localhost/sample";
      String userName = "root";
      String pasword = "tiger";
      Connection con = DriverManager.getConnection(url, userName, pasword);

      jdbc:mysql://localhost/sample
      Above string is a database connection string.

      jdbc:mysql:// = java database connection to a mysql database
      localhost = mysql database is on local machine
      sample = name of database being connected to

Step 4: Execute queries
/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);
        
        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
 rs.close();
        conn.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun

String url = "jdbc:mysql://localhost/sample";

In the above string,'sample' is the database name. You can create database using below sql command.

CREATE DATABASE sample;






Prevoius                                                 Next                                                 Home

Start working with JDBC

There is no driver packaged with JDBC API, you must get the driver from specific vendor. In this tutorial, I am going to use MySQL driver. I downloaded 'com.mysql.jdbc_5.1.5.jar' file from 'http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm'
and set it in the class path.

Prevoius                                                 Next                                                 Home

Remove table

By using 'DROP TABLE' statement, you can remove a table.

Syntax
DROP TABLE table_name;

mysql> DROP table employee;
Query OK, 0 rows affected (0.05 sec)

mysql> select * from employee;
ERROR 1146 (42S02): Table 'sample.employee' doesn't exist


Prevoius                                                 Next                                                 Home