By kswaughs | Wednesday, December 2, 2015

How to get IBM DB2 database connection in Java

In Java, java.sql.Connection object is used to perform several database operations.
Following are the different ways of creating the connection object of IBM DB2 database.

1) Using DriverManager
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class IBMDB2Connection {

    public Connection createConnection() {

        Connection con = null;
 
        try {

            Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
            String url = "jdbc:db2://servername:portnumber/databasename";
            String userId = "username_value";
            String password = "password_value";

            con = DriverManager.getConnection(url, userId, password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return con;
    }
}

2) Using DataSource provided by IBM DB2
import java.sql.Connection;
import java.sql.SQLException;

import com.ibm.db2.jcc.DB2SimpleDataSource;

public class IBMDB2DataSourceConnection {

    public Connection createConnection() {
  
        Connection con = null;
        DB2SimpleDataSource db2ds = new DB2SimpleDataSource();
        db2ds.setDatabaseName("databasename");
        db2ds.setUser("username_value");
        db2ds.setPassword("password_value");
        db2ds.setPortNumber(portnumber);
  
        try {
            con = db2ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;
    } 
} 

When you are done with SQL operations on above Connection object, Below is the method to close the connection object.

Method to close the connection
public void closeConnection(Connection con) {
    try {
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Recommend this on


No comments:

Post a Comment