Wednesday, 23 January 2013

Connection of Java program with DB2 database


Connection of Java program with DB2 database

For connecting a Java program to DB2, we need the following software :
1) Jdk (any version)
2) DB2
3) DB2 Driver (db2jcc.jar & db2jcc4.jar )

Download db2jcc.jar & db2jcc4.jar from the link provided below :

http://www.ziddu.com/download/21414620/DB2_Driver.zip.html

Open the downloaded zip file to get db2jcc.jar & db2jcc4.jar files.

Few steps in DB2 :  After installing DB2, open the command prompt and type
       "clpplus  <username>@localhost:50000/<database_name>"
For ex :
        C: \Users\Mayank>clpplus db2admin@localhost:50000/sample

Now create table using sql commands and insert values in it and commit.

Set CLASSPATH of DB2 Driver :
Set the location of db2jcc.jar & db2jcc4.jar  in the environment variable CLASSPATH .


The Java Program shown below insert values in the table project already created in the database and retrieve the table data on the console.          
In the following program,
         table name = project
         username = db2admin (given by user during installation)
         password = db2admin (given by user during installation) 
         database = sample (default database of DB2) 

Java Program :

import java.sql.*;
public class DBCdb2
{public static void main(String args[]) throws Exception
{Class.forName("com.ibm.db2.jcc.DB2Driver");
Connection con = DriverManager.getConnection("jdbc:db2://172.16.2.38:50000/sample","db2admin","db2admin");
Statement st= con.createStatement();
int i3=st.executeUpdate("insert into project values('mayank',21)");   // insertion of values
int i4=st.executeUpdate("insert into project values('vikash',21)");     // insertion of values
ResultSet rs = st.executeQuery("select * from project");
while(rs.next())
System.out.println(rs.getString(1)+"    "+rs.getString(2));
rs.close();
st.close();
con.close();
}
}


Note :  In case of database like DB2, we need to download the jar file containing Driver class(es) (db2jcc.jar & db2jcc4.jar in case of DB2 database) separately and then set their classpath as they are not supplied along with the database software.

No comments:

Post a Comment