Wednesday, 1 October 2014

SQLWarning class

SQLWarning represents an exception that provides information on database access warnings. You can retrieve warnings from Connection, Statement, and ResultSet objects.

Connection, Statement and ResultSet interfaces provides getWarnings method which retrieves the first warning reported by calls on this object.

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

public class SampleApp {
    static Connection conn;
    static Statement stmt;
    static ResultSet rs;
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* 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/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    static void getConnectionWarnings() throws SQLException{
        /* To get the warnings generated by connection object */
        System.out.println("Warnings generated by connection");
        System.out.println("--------------------");
        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            String message = warning.getMessage();
            String sqlState = warning.getSQLState();
            int errorCode = warning.getErrorCode();
            System.out.println(message + " " + sqlState +" " + errorCode);
            warning = warning.getNextWarning();
        }
    }
    
    static void getStatementWarnings() throws SQLException{
        System.out.println("Warnings generated by statement");
        System.out.println("--------------------");
        SQLWarning warning = stmt.getWarnings();
        while (warning != null) {
            String message = warning.getMessage();
            String sqlState = warning.getSQLState();
            int errorCode = warning.getErrorCode();
            System.out.println(message + " " + sqlState +" " + errorCode);
            warning = warning.getNextWarning();
        }
    }
    
    static void getResultSetWarnings() throws SQLException{
        System.out.println("Warnings generated by Result set");
        System.out.println("--------------------");
        SQLWarning warning = rs.getWarnings();
        while (warning != null) {
            String message = warning.getMessage();
            String sqlState = warning.getSQLState();
            int errorCode = warning.getErrorCode();
            System.out.println(message + " " + sqlState +" " + errorCode);
            warning = warning.getNextWarning();
        }
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        
        conn = getConnection();
                
        conn.setAutoCommit(false);
          /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        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);
        
        conn.rollback();
        
        query = "SELECT * FROM employee";
        rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        query = "DROP TABLE employee";
        stmt.execute(query);
        
        getConnectionWarnings();
        getStatementWarnings();
        getResultSetWarnings();
        
    rs.close();
        stmt.close();
        conn.close();
    }
}


Prevoius                                                 Next                                                 Home

Get Driver details

java.sql.DatabaseMetaData interface provides below methods to get driver details.

int getDriverMajorVersion()
Return this JDBC driver's major version number.

int getDriverMinorVersion()
Return this JDBC driver's minor version number.

String getDriverName()
Return the name of this JDBC driver.

String getDriverVersion()
Returns the version number of this JDBC driver as a String.

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

public class SampleApp {
    
    static Connection conn;
    static Statement stmt;
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* 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/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{      
       
        conn = getConnection();
        DatabaseMetaData dm = conn.getMetaData();
        
        System.out.println("Major Version: " +dm.getDriverMajorVersion());
        System.out.println("Minor Version: " +dm.getDriverMinorVersion());
        System.out.println("Driver Name: " +dm.getDriverName());
        System.out.println("Driver Version: " +dm.getDriverVersion());
        
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Major Version: 5
Minor Version: 1
Driver Name: MySQL-AB JDBC Driver
Driver Version: mysql-connector-java-5.1.5 ( Revision: ${svn.Revision} )


Prevoius                                                 Next                                                 Home

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

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

get Connection object using Driver interface

It is a three step process.
Step 1: Load the driver
Ex: Class.forName("com.mysql.jdbc.Driver");

Step 2: Get the Driver instance
Ex: Driver driver = DriverManager.getDriver("jdbc:mysql://localhost/world");

Step 3: Use the connect method of Driver interface, to connect to database.
Ex: Connection conn = driver.connect("jdbc:mysql://localhost/world", props);

import java.sql.*;
import java.util.*;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        Class.forName("com.mysql.jdbc.Driver");
        Driver driver = DriverManager.getDriver("jdbc:mysql://localhost/world");
        Properties props = new Properties();
        
        String userName = "root";
        String password = "tiger";
        
        props.put("user", userName);
        props.put("password", password);
        
        Connection conn = driver.connect("jdbc:mysql://localhost/world", props);
        
        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();
        conn.close();

    }
}

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



Prevoius                                                 Next                                                 Home

Get Connection object using DriverManager class

DriverManager class provides 'getConnection' method to connect to a database.
'getConnection' is a static method for getting connections and available in three variants.

public static Connection getConnection(String url)
DriverManager attempts to establish a connection to the given database URL. The DriverManager select an appropriate driver from the set of registered JDBC drivers.

public static Connection getConnection(String url, Properties info)
DriverManager attempts to establish a connection to the given database URL. The DriverManager select an appropriate driver from the set of registered JDBC drivers. 'info' is a list of arbitrary string tag/value pairs as connection arguments. Normally at least a "user" and "password" property should be included

public static Connection getConnection(String url, String user, String password)
DriverManager attempts to establish a connection to the given database URL. The DriverManager select an appropriate driver from the set of registered JDBC drivers.

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

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* 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/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{      
        Connection conn = getConnection();
        conn.setAutoCommit(false);
          /* 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 = "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();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Calling roll back operation
1 Krishna
2 Arjun
3 Joel
Dropping table employee





Prevoius                                                 Next                                                 Home

various ways to create Connection object

You can create a Connection object in more than one way.
    a. Using java.sql.DriverManager class
    b. Using Java.sql.Driver interface
    c. Using javax.sql.DataSource interface
    d. Using javax.sql.PooledConnection interface



Prevoius                                                 Next                                                 Home