package com.bjpowernode.drp.util;
import java.net.ConnectException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.sun.org.apache.bcel.internal.generic.NEW;
/**
* 采用ThreadLocal封装Connection,可以防止线程安全
* @author LLS
*
*/
public class ConnectionManager {
private static ThreadLocal<Connection> connectionHolder=new ThreadLocal<Connection>();
/**
* 得到Connection
* @return
*/
public static Connection getConnection()
{
//如果再当前线程中已经绑定相应的Connection则取出来
Connection conn=connectionHolder.get();
//如果没有绑定
if (conn==null) {
try{
JdbcConfig jdbcConfig=xmlConfigReader.getInstance().getJdbcConfig();
Class.forName(jdbcConfig.getDriverName());
conn=DriverManager.getConnection(jdbcConfig.getUrlName(), jdbcConfig.getUserName(), jdbcConfig.getPasswordName());
//将Connection设置到变量ThreadLocal中
connectionHolder.set(conn);
}catch(ClassNotFoundException e){
e.printStackTrace();
throw new ApplicationException("系统错误,请联系管理员!");
} catch (SQLException e) {
e.printStackTrace();
throw new ApplicationException("系统错误,请联系管理员!");
}
}
return conn;
}
public static void close(Statement pstmt)
{
if(pstmt !=null)
{
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭结果集
* @param rs
*/
public static void close(ResultSet rs)
{
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭连接
*/
public static void closeConnection()
{
Connection conn=connectionHolder.get();
if (conn!=null) {
try {
conn.close();
//从集合ThreadLocal中清除掉
connectionHolder.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 开启事务
* @param conn
*/
public static void beginTransation(Connection conn)
{
try {
if(conn!=null)
{
if(conn.getAutoCommit())
{
conn.setAutoCommit(false);
}
}
} catch (Exception e) {
}
}
/**
* 提交事务
* @param conn
*/
public static void commitTransation(Connection conn)
{
try {
if(conn!=null)
{
if(!conn.getAutoCommit())
{
conn.commit();
}
}
} catch (Exception e) {
}
}
/**
* 回滚事务
* @param conn
*/
public static void rollbackTransation(Connection conn)
{
try {
if(conn!=null)
{
if(!conn.getAutoCommit())
{
conn.rollback();
}
}
} catch (Exception e) {
}
}
/**
* 重启事务
* @param conn
*/
public static void resetTransation(Connection conn)
{
try {
if(conn!=null)
{
if(conn.getAutoCommit())
{
conn.setAutoCommit(false);
}else
{
conn.setAutoCommit(true);
}
}
} catch (Exception e) {
}
}
}