【跟我学apache-commons(三)】DBCP2.2---JavaSE配置DBCP连接池

maven配置

依赖:
 <!--dbcp -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.1</version>
		</dependency>
		
		<!-- mysql驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.32</version>
		</dependency>

maven配置后的工程目录:
【跟我学apache-commons(三)】DBCP2.2---JavaSE配置DBCP连接池_第1张图片

javase程序为

package com.laifucard.test.test_dbcp2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

/**
 * @ClassName: Test
 * @Description: 
 * @author [email protected]
 * @date 2015年6月11日 下午2:16:32 
 */
public class Test {
	public static void main(String[] args) throws Exception {
		// 1.获取数据源BasicDataSource(两种方式1-直接set 2-从外部文件 两种方式如下)

		// BasicDataSource bs = new BasicDataSource();
		// bs.setDriverClassName("com.mysql.jdbc.Driver");
		// bs.setUsername("root");
		// bs.setPassword("123456");
		// bs.setUrl("jdbc:mysql://localhost:3306/person?useUnicode=true&characterEncoding=utf-8");

		Properties pro = new Properties();
		pro.load(Test.class.getClassLoader().getResourceAsStream("DB.properties"));

		BasicDataSource bs = BasicDataSourceFactory.createDataSource(pro);

		// 2.获取连接Connection
		Connection conn = bs.getConnection();

		// 3.获取PreparedStatement
		PreparedStatement ps = conn.prepareStatement("select  * from meet_user LIMIT  0,6");

		// 4.获取结果集ResultSet
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			for (int i = 1; i <= 3; i++) {
				System.out.print(rs.getString(i) + "   ");

			}
			System.out.println();
		}

		// 5.关闭结果集、预处理、连接、数据源
		rs.close();

		ps.close();

		conn.close();

		bs.close();

	}
}

数据库配置文件为

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/person?useUnicode=true&characterEncoding=utf-8
username=root
password=123456


总结:

 

你可能感兴趣的:(【跟我学apache-commons(三)】DBCP2.2---JavaSE配置DBCP连接池)