Java Sample Code to connect to DB2 Database using JDBC Driver

The following example code is for connecting and accessing DB2 database. It loads the DB2 JDBC Driver and connects to the DB2 database Student and prints the records of the qual table. For running the program you have to do the following. Assume that Student database , qual table already been created in DB2.

1. Download DB2 JDBC driver.
2. Include db2 driver path in the CLASSPATH

Steps to include to db2 drivers in the class path
copy the db2 driver files db2jcc.jar, db2jcc_license_cisuz.jar, db2jcc_license_cu.jar, db2java.zip to any folder for example d:\db2drivers. Now set the classpath to include the driver files as follows.

d:\javaonline>set CLASSPATH=.;d:\db2drivers\db2jcc.jar;d:\db2drivers\db2jcc_license_cisuz.jar;d:\db2drivers\db2jcc_license_cu.jar;d:\db2drivers\db2java.zip;.

OR permanantly set by Right click on MyComputer ->Advanced Tab – > Environment variables – > select CLASSPATH and edit, set the variable value to above path. For running in Servlet / DAO in struts include the above driver files in the libraries (WebContent\WEB-INF\lib). If you use any developer tool like WSAD, Myeclipe, Use Add External Jar from Project -> Java Build Path -> Libraries Tab -> Add External Jars.


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

public class DB2Connect {
 public static void main(String[] argv) {
 try {
 Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
 } catch (ClassNotFoundException e) {
 System.out.println("Please include Classpath Where your DB2 Driver is located");
 e.printStackTrace();
 return;
 }
 System.out.println("DB2 driver is loaded successfully");
 Connection conn = null;
 PreparedStatement pstmt = null;
 ResultSet rset=null;
 boolean found=false;
 try {
 conn = DriverManager.getConnection("jdbc:db2:student");
 if (conn != null)
 {
 System.out.println("DB2 Database Connected");
 }
 else
 {
 System.out.println("Db2 connection Failed ");
 }
 pstmt=conn.prepareStatement("Select * from qual");
 rset=pstmt.executeQuery();
 if(rset!=null)
 {
 while(rset.next())
 {
 found=true;
 System.out.println("Class Code: "+rset.getString("clcode"));
 System.out.println("Name: "+rset.getString("name"));
 }
 }
 if (found ==false)
 {
 System.out.println("No Information Found");
 }
 } catch (SQLException e) {
 System.out.println("DB2 Database connection Failed");
 e.printStackTrace();
 return;
 }
 }
 }

Output if the qual table has 3 records

D:\javaonline>java DB2Connect

DB2 driver is loaded successfully

DB2 Database Connected

Class Code: 1

Name: MCA

Class Code: 2

Name: BE

Class Code : 3

Name : BTech

You may also like

Leave a Reply

1 Comment on "Java Sample Code to connect to DB2 Database using JDBC Driver"


Guest
joey
6 months 9 days ago

where do i get the driver??