c3p0数据库连接池实例

c3p0下载地址:http://download.csdn.net/detail/huhui_bj/6944595

这篇文章介绍的是,在普通Java Web工程中或者普通Java工程中使用c3p0数据库连接池的实例,c3p0的jar文件包括3个。下面这个实例工程中,主要包括三个重要的文件:
C3P0ConnentionProvider.java       初始化c3p0数据库连接池

SQLHelper.java         通过数据库连接池,提供对数据库的增删改查功能

c3p0.properties  c3p0的配置文件

工程文件的截图如下:



c3p0.properties文件内容如下:

#jdbc基本信息
driverClass=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:orcl
user=scott
password=tigger

#c3p0连接池信息
c3p0.minPoolSize=3
c3p0.maxPoolSize=25

#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数
c3p0.acquireIncrement=3
#定义在从数据库获取新连接失败后重复尝试的次数
c3p0.acquireRetryAttempts=60
#两次连接中间隔时间,单位毫秒
c3p0.acquireRetryDelay=1000
#连接关闭时默认将所有未提交的操作回滚 
c3p0.autoCommitOnClose=false
#当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限
c3p0.checkoutTimeout=3000
#每120秒检查所有连接池中的空闲连接。Default: 0
c3p0.idleConnectionTestPeriod=120
#最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0  
c3p0.maxIdleTime=600
#如果设为true那么在取得连接的同时将校验连接的有效性。Default: false  
c3p0.testConnectionOnCheckin=false
#如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
c3p0.maxStatements=8
#maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
c3p0.maxStatementsPerConnection=5


C3P0ConnentionProvider.java文件内容如下:

package com.hh.db;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.DataSources;

/**
 * c3p0连接池管理类
 */
public class C3P0ConnentionProvider {

	private static final String JDBC_DRIVER = "driverClass";
	private static final String JDBC_URL = "jdbcUrl";

	private static DataSource ds;
	/**
	 * 初始化连接池代码块
	 */
	static {
		initDBSource();
	}

	/**
	 * 初始化c3p0连接池
	 */
	private static final void initDBSource() {
		Properties c3p0Pro = new Properties();
		try {
			// 加载配置文件
			String path = C3P0ConnentionProvider.class.getResource("/").getPath();
			String websiteURL = (path.replace("/build/classes", "").replace("%20"," ").replace("classes/", "") + "c3p0.properties").replaceFirst("/", "");
			FileInputStream in = new FileInputStream(websiteURL);
			c3p0Pro.load(in);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String drverClass = c3p0Pro.getProperty(JDBC_DRIVER);
		if (drverClass != null) {
			try {
				// 加载驱动类
				Class.forName(drverClass);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}

		}

		Properties jdbcpropes = new Properties();
		Properties c3propes = new Properties();
		for (Object key : c3p0Pro.keySet()) {
			String skey = (String) key;
			if (skey.startsWith("c3p0.")) {
				c3propes.put(skey, c3p0Pro.getProperty(skey));
			} else {
				jdbcpropes.put(skey, c3p0Pro.getProperty(skey));
			}
		}

		try {
			// 建立连接池
			DataSource unPooled = DataSources.unpooledDataSource(c3p0Pro.getProperty(JDBC_URL), jdbcpropes);
			ds = DataSources.pooledDataSource(unPooled, c3propes);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取数据库连接对象
	 * 
	 * @return 数据连接对象
	 * @throws SQLException
	 */
	public static synchronized Connection getConnection() throws SQLException {
		final Connection conn = ds.getConnection();
		conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
		return conn;
	}
}

SQLHelper.java文件内容如下:

/**
 * 功能:提供统一的查询、修改和插入方法
 */
package com.hh.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SQLHelper {
	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;

	/**
	 * 数据查询
	 * @param sql语句
	 * @return 返回结果集List<Object>
	 */
	public List<Object> query(String sql) {
		if(sql.equals("") || sql == null){
			return null;
		}
		List<Object> list = new ArrayList<Object>();
		try {
			conn = C3P0ConnentionProvider.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			// 可以得到有多少列
			int columnNum = rsmd.getColumnCount();
			// 将数据封装到list中
			while (rs.next()) {
				Object[] objects = new Object[columnNum];
				for (int i = 0; i < objects.length; i++) {
					objects[i] = rs.getObject(i + 1);
				}
				list.add(objects);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 插入、修改数据操作
	 * @param sql语句
	 * @return boolean 成功返回true,失败返回false
	 */
	public boolean update(String sql) {
		boolean b = false;
		if(sql.equals("") || sql == null){
			return b;
		}
		try {
			conn = C3P0ConnentionProvider.getConnection();
			ps = conn.prepareStatement(sql);
			int i = ps.executeUpdate();
			if (i == 1) {
				b = true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return b;
	}

}

至于Demo.java文件,可提供参考的内容如下:

/**
 * SQLHelper的测试类
 * 
 */
package com.hh.db;

import java.util.ArrayList;
import java.util.List;


public class Demo {
	
	private SQLHelper sqlHelper = new SQLHelper();
	
	/**
	 * 测试query
	 */
	/*public void testQuery(){
		String sql = "select * from crh2_station where id = 1";
		List list = sqlHelper.query(sql);
		List<Crh2Station> crh2StationList = new ArrayList<Crh2Station>();
		//对查询结果进行封装
		for (int i = 0; i < list.size(); i++) {
			Object object[] = (Object[]) list.get(i);
			Crh2Station crh2Station = new Crh2Station();
			crh2Station.setId(Integer.parseInt(object[0].toString()));
			crh2Station.setSlopeId(Integer.parseInt(object[1].toString()));
			crh2Station.setSlope(Double.parseDouble(object[2].toString()));
			crh2Station.setLength(Double.parseDouble(object[3].toString()));
			crh2Station.setEnd(Double.parseDouble(object[4].toString()));
			crh2Station.setHeight(Double.parseDouble(object[5].toString()));
			crh2StationList.add(crh2Station);
		}
		return crh2StationList;
	}*/
	
	/**
	 * 测试insert、update、delete
	 */
	/*public void testInsertOrUpdate(){
		String sql = "delete from crh2_station where id = 1";
		boolean b = sqlHelper.update(sql);
		if(b){//b为true则操作成功
			System.out.println("操作成功");
		}else{//b为false则操作失败
			System.out.println("操作失败");
		}
	}*/

}


参考资料:http://blog.csdn.net/wushangjimo/article/details/12654491




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。