本文讲述了在Windows平台上,使用eclipse连接DB2数据库的过程
环境:
Windows 7, 64bit
DB2 10.5FP4
Eclipse Mars Release (4.5.0) (安装eclipse之前,要确保已经安装了java,如果eclipse是64bit的,得先安装64bit的JAVA,不然在启动eclipse的时候可能会报错java was started but returned code=13)
过程如下
1.) 在DB2server端要保证端口处于监听状态
2.) 打开eclipse,新建一个项目JavaTest01,在项目名称上点击右键,选择“Build Path” -> “Add External Archives...”
3.) 在弹出的对话框里,进入到DB2的安装目录里,选择db2 jdbc驱动,我这儿选择的是db2jcc4.jar
4.) 之后,就可以编写示例代码了,我的如下:
import java.sql.*;
public class FirstClass {
public static void main(String args[]) {
try {
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
String url = "jdbc:db2://localhost:50000/SAMPLE";
String user = "miaoqingsong";
String password = "mypassword";
System.out.println("try");
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("success");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM MIAOQINGSONG.T1");
ResultSet rs = ps.executeQuery();
while (rs.next())
{
int id = rs.getInt("ID");
String name = rs.getString("NAME");
System.out.println("ID: " + id );
System.out.println("NAME: " + name);
}
conn.close();
} catch (Exception sqle) {
System.out.println(sqle);
}
return;
}
}
5.) 运行,得到如下结果:
try
success
ID: 995
NAME: miaoqingsong
ID: 786
NAME: zhanglei
参考:
http://www.yiibai.com/jdbc/jdbc_quick_guide.html