java连接db2

java连接db2。 其实还是比较简单的。 开始找了几篇文章都写得我心惊胆战的。

下面是关于JDBC驱动的四种类型: from DB2 and Java

According to the JDBC specification, there are four types ofJDBC driver architectures:

  • Type 1 - drivers that implement the JDBC API as amapping to another data access API, such as Open DatabaseConnectivity (ODBC). Drivers of this type are generally dependenton a native library, which limits their portability. The JDBC-ODBC Bridge driver is an example of a Type 1 driver.
  • Type 2 - drivers that are written partly in the Java programming language and partly in native code. The drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited.
  • Type 3 - drivers that use a pure Java client and communicate with a middle ware server using a database-independent protocol. The middle ware server then communicates the client's requests to the data source.
  • Type 4 - drivers that are pure Java and implement thenetwork protocol for a specific data source. The client connects directly to the data source.

稍做解释:

type1: JDBC API是实现于ODBC的api。 这个驱动完全依赖于官方的库。 所以移植性非常差。

type2: JDBC驱动的部分实现是用用java写的,部分是native code。所以当连接之后呢,驱动还需要用一个native客户端的库来和数据库进行交互。移植性也是很差的。

type3: 驱动可以用纯java写的客户端与一个中间服务器进行交互。

type4: 驱动是用纯Java实现的,而且它的客户端可以直接访问数据资源。当然这种事最好的啦。 可移植性最好。

看到这,果断用第四种类型的JDBC啊。


Jar包: db2jcc4.jar, db2jcc_licsence_cu.jar

是从C:\Program Files\IBM\SQLLIB\java 下拷出这两个jar包的(因为db2装在我的虚拟机里)。

导入到工程里面。 接下来就是代码了。 我的db2 是v9.7版的。

try 
		{
	         Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
	        
	         String url="jdbc:db2://192.168.1.19:50000/TEST";
	         String user="db2admin";
	         String password="1";
	         
	         System.out.println("try");
	         Connection conn= DriverManager.getConnection(url,user,password);
	         System.out.print("success ");
	        
//	         PreparedStatement  ps=conn.prepareStatement("select * from administrator.student ");
//	         
//	         ResultSet rs=ps.executeQuery();
//	         
//	         while (rs.next())
//	         {
//	        	 String name = rs.getString(2);
//	            System.out.println(name);
//	         }
	    
	        conn.close();
			         
        }catch(Exception sqle)
        {
        	System.out.print(sqle);
        }

连接成功。

说个小插曲,我开始把端口号搞错了, 我以为是5000。

结果老是报 消息为:Connection refused: connect。 ERRORCODE=-4499, SQLSTATE=08001

后面我查db2的端口号才看清楚是50000。

如有问题, 欢迎指正。 谢谢。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值