62,615
社区成员
发帖
与我相关
我的任务
分享
package com.towery.util.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
/**
* 数据库连接类
*/
public class DBAccess {
private static BasicDataSource dataSource;
private static ThreadLocal<Connection> tl
= new ThreadLocal<Connection>();
/**
* 读取配置文件
*/
static {
try {
dataSource = new BasicDataSource();
Properties props = new Properties();
props.load(DBAccess.class.getClassLoader().getResourceAsStream("db.properties"));
//System.out.println("url: "+props.getProperty("url"));
dataSource.setDriverClassName(props.getProperty("driverClass"));
dataSource.setUrl(props.getProperty("url"));
dataSource.setUsername(props.getProperty("username"));
dataSource.setPassword(props.getProperty("password"));
dataSource.setMaxActive(30);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获得数据库的连接对象Connection,获得的是同一个Connection对象
* @return 连接对象Connection
* @throws SQLException 抛出SQL异常
*/
public synchronized static Connection getConnection() throws SQLException {
Connection con = (Connection) tl.get();
if (con == null) {
Tool.print("获取数据库连接");
System.out.println(dataSource.getNumIdle());
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
/**
* 释放数据库的连接
*/
public static void closeConnection() {
try {
Connection con = (Connection) tl.get();
if (con != null) {
con.close();
tl.set(null);
}
} catch (SQLException e) {
}
}
/**
* 开始事务
*/
public static void beginTx() {
try {
Connection con = getConnection();
con.setAutoCommit(false);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 事务的提交
*/
public static void commitTx() {
try {
Connection con = getConnection();
con.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/*
* 事务的回滚
*/
public static void rollbackTx() {
try {
Connection con = getConnection();
con.rollback();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//测试连接是否成功
public static void main(String[] args) throws Exception {
Tool.print("1111");
for(int i=0;i<100;i++){
Connection con = DBAccess.getConnection();
// DBAccess.closeConnection();
}
}
}