1.安装好db2数据库,并建立表如下:
2.eclipse或myeclipse中建立工程并导入java连接db2所需要的jar包db2java.jar 下载地址:
3.建立iConn接口,代码如下:
4.建立连接db2类实现iConn接口,代码如下:
注意修改数据库名,用户名和密码
package com.zhaochao.dba;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB2Conn implements iConn {
private static final String DBDRIVER = "COM.ibm.db2.jdbc.app.DB2Driver" ;
private static final String DBURL = "jdbc:db2:zhaochao" ;
private static final String DBUSER = "" ;
private static final String DBPASS = "";
private Connection conn=null;
@Override
public Connection getConn() {
// TODO Auto-generated method stub
try {
Class.forName(DBDRIVER);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Driver");
e.printStackTrace();
}
try {
this.conn=DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("getDriver failed!");
e.printStackTrace();
}
return conn;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
5.测试连接
package com.zhaochao.dba;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// TestMySQL();
// TestOracle();
TestDB2();
// TestSQLServer();
// TestAccess();
}
private static void TestDB2() {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
iConn iconn=new DB2Conn();
conn=iconn.getConn();
String sql="select * from person";
try {
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
6,测试结果: