下面介绍一下在应用程序中如何使用Type4驱动访问DB2:
1. 数据库的驱动可以在安装DB2的文件夹中找到,文件名是db2jcc.jar.(本人的是安装在D盘,db2jcc.jar这个文件位于D:/Program Files/IBM/SQLLIB/java目录下);
2. 创建DB2中创建数据库时一定要指定数据库的代码集为: UTF-8;否则程序运行时会抛出"com.ibm.db2.jcc.b.DisconnectException: encoding not supported!!"异常.
下面给出源码供大家一起交流:
package test.object;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB2Type4 {
private String host;
private String database;
private String user;
private String password;
public DB2Type4() {
super();
}
public DB2Type4(String host, String database, String user, String password) {
this.host = host;
this.database = database;
this.user = user;
this.password = password;
}
public Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
System.out.println("成功加载了DB2驱动");
} catch (ClassNotFoundException e) {
System.out.println("加载DB2驱动失败");
e.printStackTrace();
}
try {
conn = DriverManager.getConnection("jdbc:db2://" + this.host + "/"
+ this.database, this.user, this.password);
System.out.println("成功获得DB2连接");
} catch (SQLException e) {
System.out.println("获得DB2连接失败");
e.printStackTrace();
}
return conn;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
/**
* @param args
*/
public static void main(String[] args) {
DB2Type4 test = new DB2Type4();
test.setHost("192.168.1.15:50000");
test.setDatabase("test");
test.setUser("db2admin");
test.setPassword("ibm");
test.getConnection();
DB2Type4 test2 = new DB2Type4("192.168.1.15:50000", "test", "db2admin",
"ibm");
test2.getConnection();
}
}