日期:2014-05-16  浏览次数:20405 次

JDBC-DBCP数据库连接池的一个小例子

一个简单的数据库连接池的小例子,如何使用jdbc获取mysql数据库连接
package cn.guangpeng.jdbc;

public class TestResultSet {

	public static void main(String[] args) throws Exception {
		Connection connection = null;
		Statement st = null;
		ResultSet rs = null;

		try {
			connection = getConnection();

			st = connection.createStatement();

			String sql = "SELECT id, age,name FROM customer";

			rs = st.executeQuery(sql);

			while (rs.next()) {
				// 1,2,3分别为为每列所对应的字段
				String id = rs.getString(1);
				String age = rs.getString(2);
				String name = rs.getString(3);

				System.out.println("id  :" + id + ", age :" + age + ", name :"
						+ name);
			}
		} finally {
			// 最后一定要关闭连接
			releaseResource(connection, st, rs);
		}

	}

	//先打开的链接后断开,就和人脱衣服一样,先穿的后脱,呵呵
	private static void releaseResource(Connection connection, Statement st,
			ResultSet rs) throws Exception {
		try {
			if (rs != null)
				rs.close();
		} finally {
			try {
				if(st != null)
					st.close();
			} finally {
				if (connection != null)
					connection.close();
			}
		}

	}

	private static Connection getConnection() throws Exception {
		// 准备四个必须的数据
		String driverClass = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/itcast";
		// jdbc: 协议名, mysql: 子协议名, localhost:3306/itcast: 子名称
		// localhost:数据库服务器的 ip, 3306 数据库服务器的端口号, itcast: 数据库名
		String user = "root";
		String password = "root";

		// 2.加载数据库的驱动程序,实例化
		Class.forName(driverClass);
		// 3. 调用 DriverManager 的 getConnection(url, user, password) 获取数据库连接
		Connection connection = DriverManager.getConnection(url, user, password);

		return connection;
	}

}



关于对ResultSet详细的用法,可以访问此博客
引用
http://www.blogjava.net/fadesea/archive/2006/03/07/33965.aspx

如果运行该程序,需要对数据库参数进行更改,还有要引入DBCP的jar包commons-dbcp-1.2.2.jar;commons-pool-1.3.jarmysql-connector-java-5.1.7-bin.jar