Wednesday 1 October 2014

Load Driver using System.properties

By using 'setProperty' method of System class, you can load JDBC driver into JVM.

System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");

/* 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");  
       
        System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
        System.out.println(System.getProperty("jdbc.drivers"));
         
        /* 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
com.mysql.jdbc.Driver
Connecting to database
1 Krishna
2 Arjun
Dropping table employee

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment