Using JDBC for DB2 connectivity

As part of IBM’s “Java Everywhere” strategy, IBM has provided the OS/390 Java programmer with two access mechanisms to access DB2 data. In this article I’ll explain how to make DB2 connection using JDBC.

First of all you need to download driver. You can download respective db2jcc or db2jcc4 jar file from or use maven:

<!-- -->

Driver name is depends on the driver we are using. 

Use when is in your path. 

Use when db2jcc.jar & db2jcc_license_cu.jar are in your classpath. 

package com.outhints.testdb2;

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

 * This program demonstrate how to establish database connection to DB2
 * @author

public class TestDB2Connection {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	Connection conn= null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
		String dbURL= "jdbc:db2://localhost:50001/MyDBName";
		String user = "USRERID";
		String password = "Password";
		try {
			//Load the driver
		} catch (ClassNotFoundException ex) {
			// TODO Auto-generated catch block
			System.out.println("Please include Classpath where your DB2 Driver is located.");
		System.out.println("DB2 Driver loaded successfully.");
		Boolean found = false;
		Properties prop = new Properties();   // Create Properties Object
		//Set User ID
		prop.put("user", user);
		//Set Password
		prop.put("password", password);
		//Set securityMechanism
		prop.put("securityMechanism", new String(""+ DB2BaseDataSource.ENCRYPTED_USER_AND_PASSWORD_SECURITY + ""));
		//Set encryptionAlorithm
		prop.put("encryptionAlorithm", "2");
		try {
		conn = DriverManager.getConnection(dbURL,prop);
		if(conn != null) {
			System.out.println("DB Connection is successfull");
			DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
			System.out.println("Driver Name: "+dm.getDriverName());
			System.out.println("Driver Version: "+dm.getDriverVersion());
		else {

			System.out.println("DB2 Connection Failed.");
		//Query String. Please skip Schema_Name in case not needed
		String query = "Select EMP_NAME, EMP_ID from SCHEMA_NAME.EMP ";
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		if(rs != null) {
			while (
				System.out.print("EmployeeName : " + rs.getString(1));
				System.out.println(", Employee ID : " + rs.getString(2));
		if(found = false)
			System.out.println("No Information Returned.");
	} catch (Exception e) {
		// TODO: handle exception
	finally {
		try {
				if(conn != null &amp;&amp; !conn.isClosed())
		} catch (SQLException e2) {
			// TODO: handle exception


Leave a Reply

Your email address will not be published. Required fields are marked *