Wednesday, 1 October 2014

get Connection object using DataSource interface

javax.sql.DataSource interface provides 'getConnection()' method to get Connection to a database.

'getConnection' method available in two variants.
    Connection getConnection() throws SQLException
    Connection getConnection(String username, String password)

It is recommended now that connection objects should be created by the DataSource implementation class.

'com.mysql.jdbc.jdbc2.optional.MysqlDataSource' class implements DataSource interface.

import java.sql.*;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        Class.forName("com.mysql.jdbc.Driver");
        
        /* Get Connection using DataSource */
        MysqlDataSource ds = new MysqlDataSource();
        ds.setServerName("localhost");
        ds.setDatabaseName("world");
        ds.setUser("root");
        ds.setPassword("tiger");
      
        try (Connection conn = ds.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