c3p0数据库连接池使用--创建JDBCTools 公共类

package com.atguigu.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCTools {

//处理数据库事务的
//提交事务
public static void commit(Connection connection){
if(connection!=null){
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//回滚事务
public static void rollback(Connection connection){
if(connection!=null){
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//开始事务
public static void beginTx(Connection connection){
if(connection!=null){
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//数据库连接池应只被初始化一次,因为一个项目只需要一个连接池,所以创建一个静态的属性然后从静态代码块中初始化
private static DataSource dataSource=null;
static{
dataSource=new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
/**
* 获取数据库连接方法
*
* @return
* @throws IOException
* @throws ClassNotFoundException
* @throws SQLException
*/

public static Connection getConnection1() throws IOException,
ClassNotFoundException, SQLException {
// 1、读取connection数据源所需四个字符串
// 1)创建properties对象
Properties properties = new Properties();
// 2)获取properties对象的输入流
InputStream inputStream = JDBCTools.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
// 3)加载输入流
properties.load(inputStream);
// 4)获取字符串
String driverClass = properties.getProperty("driverClass");
String url = properties.getProperty("jdbcUrl");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
// 2、加载驱动
Class.forName(driverClass);
// 3、用DriverManager的getConnection()方法创建 connection数据源
Connection connection=DriverManager.getConnection(url, user, password);
return connection;
}


/**
* 释放数据库资源方法
*
* @param resultSet
* @param statement
* @param connection
*/
public static void release(ResultSet resultSet, PreparedStatement preparedStatement,
Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
}
}
if (connection != null) {
try {
//数据库连接池的Connection对象进行close时并不是真的进行关闭,而是把该数据库连接归还到连接池
connection.close();
} catch (SQLException e) {
}
}
}

posted @ 2016-02-21 20:19  苍狼哂啡  阅读(252)  评论(0编辑  收藏  举报