在Java中用Type4驱动访问DB2

下面介绍一下在应用程序中如何使用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();
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值