09 March 2011

Accessing DB2 database using JDBC

1. Accessing DB2 database using Java:

Sample code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestSQL
    public static void main(String[] args)
         try {           
             // load the DB2 Driver

            Class.forName("com.ibm.db2.jcc.DB2Driver");            // establish a connection to DB2
        Connection db2Conn = DriverManager.getConnection("jdbc:db2://HOST_NAME:PORT_NUMBER/DATABASE_NAME","USER_NAME","USER_PASSWORD");
        // use a statement to gather data from the database
        Statement st = db2Conn.createStatement();
        String myQuery = "SELECT * FROM COUNTRY";
        // execute the query
            ResultSet resultSet = st.executeQuery(myQuery);
        // cycle through the resulSet and display what was grabbed
            while (resultSet.next())            {
            String id = resultSet.getString("COUNTRY_CODE");
            String name = resultSet.getString("COUNTRY_NAME");
            System.out.println(id + "\t" + name);
        // clean up resources
    } catch (ClassNotFoundException cnfe) {
    } catch (SQLException sqle) {

HOST_NAME: specifies the hostname or ipaddress if the system on which DB2 database is running. 
PORT_NUMBER: Port number on which db2 instance is running.
DATABASE_NAME: Name of the database in which tables resides.

2. Change above params in Sample code, compile java file.

3. Add db2jcc.jar in classpath
    $export CLASSPATH="$CLASSPATH:db2jcc.jar"

4. Run the Sample code

No comments:

Post a Comment