Wednesday, November 9, 2011

Simple DB2 JDBC program

To run this example you need to set db2java.jar in your classpath

Below is the tested code, you can directly run this program, Just provide correct login credentials and table name.

/* TestDB2.java */

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

public class TestDB2
{
    public static void main(String[] args) throws Exception
    {
        Connection con;
        Statement stat;
        Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");//Step 1: Loading Drivers

        con=DriverManager.getConnection("jdbc:db2:YOURSCHEMA","username","password");//Step 2: Making Connection

        stat=con.createStatement();//Step 3: Creating JDBC Statement

        String query = "select COLUMN_NAME from USER_NAME.TABLE_NAME;";

        ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Statement

        while(rset.next())//Step 5: Looping through the ResultSet
        {
            System.out.println(rset.getString(1));
        }
        stat.close();//step 6: Close the Connection and Statement
        con.close();
    }
}


Below are the known exceptions, Please follow proper steps to avoid below exceptions.


Exception in thread "main" COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver] SQL3
0082N  Security processing failed with reason "24" ("USERNAME AND/OR PASSWORD INVALID").  SQLSTATE=08001

        at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
        at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.check_return_code(UnknownSource)
        at COM.ibm.db2.jdbc.app.DB2Connection.connect(Unknown Source)
        at COM.ibm.db2.jdbc.app.DB2Connection.(Unknown Source)
        at COM.ibm.db2.jdbc.app.DB2Driver.connect(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at TestDB2.main(TestDB2.java:13)

Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc/YOURSCHEMA
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at TestDB2.main(TestDB2.java:13)

Exception in thread "main" COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/
SUN64] SQL0204N  "USER_NAME.TABLE_NAME" is an undefined name.  SQLSTATE=42704
        at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
        at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
        at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.check_return_code(UnknownSource)
        at COM.ibm.db2.jdbc.app.DB2Statement.execute2(Unknown Source)
        at COM.ibm.db2.jdbc.app.DB2Statement.executeQuery(Unknown Source)
        at TestDB2.main(TestDB2.java:19)

No comments:

Post a Comment