Wednesday 1 October 2014

Get Connection object Using PooledConnection interface

javax.sql. PooledConnection interface provides 'getConnection()' method to create and returns a Connection object.

import java.sql.*;
import javax.sql.PooledConnection;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        Class.forName("com.mysql.jdbc.Driver");
        
        MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
        ds.setServerName("localhost");
        ds.setDatabaseName("world");
        ds.setUser("root");
        ds.setPassword("tiger");
        PooledConnection pc = ds.getPooledConnection();
        
        try (Connection conn = pc.getConnection()) {
            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 = "INSERT INTO employee values(3, \"Joel\")";
            stmt.execute(query);
            
            System.out.println("Calling roll back operation");
            
            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();
        }
    }
}

Output
Calling roll back operation
1 Krishna
2 Arjun
3 Joel
Dropping table employee



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment