package cn.secondteam.utils;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DbUtil {
final static String HOST = "127.0.0.1";
final static String NAME = "root";
final static String PSW = "root";
static final String DBNAME = "bbsdb";
private static Connection connection;
public static ComboPooledDataSource dsWebgame;
static {
dsWebgame = new ComboPooledDataSource();
try {
dsWebgame.setDriverClass(DRIVER);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
// 参数由 Config 类根据配置文件读取
dsWebgame.setJdbcUrl(URL);
// 设置数据库的登录用户名
dsWebgame.setUser(USERNAME);
// 设置数据库的登录用户密码
dsWebgame.setPassword(PASSWORD);
// 设置连接池的最大连接数
dsWebgame.setMaxPoolSize(35);
// 设置连接池的最小连接数
dsWebgame.setMinPoolSize(20);
// 有时候会产生死锁,将maxStatements设置为0
dsWebgame.setMaxStatements(0);
//小于MySQL的wait timeout即可。
dsWebgame.setIdleConnectionTestPeriod(120);
}
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConnection() {
if (null == connection) {
connection=newConnection();
}
try {
if(connection.isClosed()){
connection=dsWebgame.getConnection();
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 创建数据库连接
* @return
*/
private static Connection newConnection() {
try {
return (Connection) dsWebgame.getConnection();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static void main(String args[]){
getConnection();
}
/**
* 释放资源
* @param conn
* @param st
* @param rs
*/
public static void release(Connection con, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if (st != null) {
try {
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
c3p0数据库连接池dbutil
最新推荐文章于 2022-07-20 00:39:59 发布