1)首先建立个java project,TestDB2
2)找到DB2的安装目录,我的是E:\IBM
将E:\IBM\SLIB\BIN下的:db2jdbc.dll文件拷到本机的Java_Home/bin下面,我的是D:\Program Files\Java\jdk\bin
将E:\IBM\SLIB\java下的:db2java.zip,db2jcc.jar,db2jcc_license_cu.jar考到本机,我的放到D盘下
3)在Eclipse中的TestDB2->JRE System Library 上右键,Build Path->Configure Build Path->Add External JARs,找到你刚刚考过来的db2jcc.jar,确定
4)在TestDB2的Src目录中新建一个类,testConnection,功能是:循环打印出attri数据库中表testtable的各行记录的name名称
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class testConnection {
public static void main(String[] args) {
getTable();
}
public static void getTable() {
String name = null;
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
Properties properties = new Properties();
properties.setProperty("user", "db2admin");
properties.setProperty("password", "aaaaaa");
System.out.println("start connection");
Connection conn = DriverManager.getConnection(
"jdbc:db2://192.168.2.24:50000/attri", properties);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select name from testtable");
while (rs.next())
{
name = rs.getString("name");
System.out.println(name);
}
//close connection
rs.close();
stmt.close();
conn.close();
System.out.println("close connection");
//return value
} catch (Exception e) {
System.out.println(e);
}
}
}
5)在testConnection.java上右键,run as->java application,在控制台就可以看到
start connection
xiaoming
xiaozhang
close connection
备注:服务器端(DB2)的防火墙要打开一下,要不然连接时会提示错误:
java.net.ConnectException:打开端口 50,000 上服务器/192.168.2.24 的套接字时出错,消息为:Connection refused: connect。