import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class JdbcUtils {
private static DataSource dataSource;
private static Properties prop = new Properties();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();//绑定到当前线程中
static {
try {
prop.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));//在src目录下
dataSource = BasicDataSourceFactory.createDataSource(prop);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
Connection conn = null;
try {
conn = tl.get();
if(conn==null){
conn = dataSource.getConnection();
tl.set(conn);
}
conn.setAutoCommit(false);
return conn;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void commitTransaction(){
Connection conn = null;
try {
conn= tl.get();
if(conn!=null){
conn.commit();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void closeConnection(){
Connection conn = null;
try {
conn= tl.get();
if(conn!=null){
conn.commit();
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
tl.remove();
}
}
}
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxx
username=root
password=xxxxxx
initialSize=10
maxActive=300
maxIdle=50
minIdle=5
maxWait=200000
注意:需要导入数据库驱动和dbcp连接池jar包(commons-dbcp-1.3+commons-pool)
可以去阿里云私服下载:点击打开链接