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

No comments:

Post a Comment