[摘要]
本文中描述了一个比较简单的场景: 在AIX环境下,写一个简单的JAVA程序,连接到DB2数据库并访问表的数据。
[背景知识要求]
要求对DB2和JAVA开发有一定的基础知识[环境]
$ db2levelDB21085I Instance "e97q6c" uses "64" bits and DB2 code release "SQL09076" with
level identifier "08070107".
Informational tokens are "DB2 v9.7.0.6", "s120629", "IP23414", and Fix Pack
"6".
Product is installed at "/opt/IBM/db2/V9.7.6".
AIX: 6100-08-02-1316
DB名: qsmiao
[过程]
1.) 确保数据库SERVER的端口处于监听状态
$ db2 get dbm cfg | grep -i "SVCENAME"TCP/IP Service name (SVCENAME) = db2c_e97q6c
[db2b /home/db2users/e97q6c]$ cat /etc/services | grep -i db2c_e97q6c
db2c_e97q6c 61111/tcp
[db2b /home/db2users/e97q6c]$ netstat -an | grep -i 61111
tcp4 0 0 *.61111 *.* LISTEN
2.)在FirstClass.java中编辑并保存以下代码
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:61111/qsmiao";
String user = "e97q6c";
String password = "e97q6c";
System.out.println("try");
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("success");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM E97Q6C.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;
}
}
3.) 编译并执行JAVA程序
$ /opt/IBM/db2/V9.7.6/java/jdk64/bin/javac FirstClass.java$ /opt/IBM/db2/V9.7.6/java/jdk64/bin/java FirstClass
try
success
ID: 11
NAME: hehe
ID: 22
NAME: you
ID: 33
NAME: and
[参考资料]
http://www.ibm.com/developerworks/cn/education/db2/db2-cert7337/section4.html