Java连接db2数据库(常用数据库连接五)

1.安装好db2数据库,并建立表如下:


2.eclipse或myeclipse中建立工程并导入java连接db2所需要的jar包db2java.jar 下载地址:http://download.csdn.net/detail/whzhaochao/6414981

3.建立iConn接口,代码如下:

package com.zhaochao.dba;

import java.sql.Connection;
public interface iConn {
	Connection getConn();
}
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;
	}

}

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();
				}
			}
		}
	}
}
	
	

6,测试结果:

Tom|18|USA
Jim|20|USA



posted @ 2013-10-18 17:09  赵侠客  阅读(978)  评论(0编辑  收藏  举报