20 Sep 2009
DB2 and JDBC
You need to include
- db2jcc.jar
- db2jcc_license_cu.jar
on the classpath of the application. These can be found in the java/ sub-directory of the db2 install directory (Program Files/IBM/SQLLIB for me on Windows).
Connecting
The connection server string depends on whether you are using type2 or type4.
- Type 1: JDBC-ODBC Bridge
- Type 2: Native-API/partly Java driver
- Type 3: Net-protocol/all-Java driver
- Type 4: Native-protocol/all-Java driver
Source: http://www.javaworld.com/javaworld/jw-07-2000/jw-0707-jdbc.html
Type2:
jdbc:db2:database
Type4:
jdbc:db2//server[:port]/database
Sample code
Opens a connection, executes a query and then closes the connection.
/* Load the driver */
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
/* open the connection */
Connection conn = DriverManager.getConnection(url, user, password);
Statement st = conn.createStatement();
/* Execute a simple query to test the connection */
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM myTable");
rs.next();
/* Print the query results */
System.out.println(rs.getInt(1));
/* don't forget to close the connection */
conn.close();