public
class ConnectionManager
{
public static final ThreadLocal threadLocal = new ThreadLocal();
@SuppressWarnings( "unchecked")
public static Connection getCurrentConnection()
{
Connection conn = (Connection) threadLocal.get();
if (conn == null)
{
try
{
conn = ConnectionPool.getInstance().getConnection(); // 获得连接
threadLocal.set(conn);
} catch (DBConnectionException e)
{
e.printStackTrace();
}
}
try
{
while (conn.isClosed())
{
conn = ConnectionPool.getInstance().getConnection();
threadLocal.set(conn);
}
} catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
@SuppressWarnings( "unchecked")
public static void closeConnection()
{
Connection conn = (Connection) threadLocal.get();
threadLocal.set( null);
if (conn != null)
{
try
{
ConnectionPool.getInstance().freeConnection(conn);
} catch (DBConnectionException e)
{
e.printStackTrace();
}
}
}
public static void rollback()
{
try
{
ConnectionManager.getCurrentConnection().rollback();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public static void commit()
{
try
{
ConnectionManager.getCurrentConnection().commit();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public static void setAutoCommit( boolean bool)
{
try
{
ConnectionManager.getCurrentConnection().setAutoCommit(bool);
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
{
public static final ThreadLocal threadLocal = new ThreadLocal();
@SuppressWarnings( "unchecked")
public static Connection getCurrentConnection()
{
Connection conn = (Connection) threadLocal.get();
if (conn == null)
{
try
{
conn = ConnectionPool.getInstance().getConnection(); // 获得连接
threadLocal.set(conn);
} catch (DBConnectionException e)
{
e.printStackTrace();
}
}
try
{
while (conn.isClosed())
{
conn = ConnectionPool.getInstance().getConnection();
threadLocal.set(conn);
}
} catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
@SuppressWarnings( "unchecked")
public static void closeConnection()
{
Connection conn = (Connection) threadLocal.get();
threadLocal.set( null);
if (conn != null)
{
try
{
ConnectionPool.getInstance().freeConnection(conn);
} catch (DBConnectionException e)
{
e.printStackTrace();
}
}
}
public static void rollback()
{
try
{
ConnectionManager.getCurrentConnection().rollback();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public static void commit()
{
try
{
ConnectionManager.getCurrentConnection().commit();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public static void setAutoCommit( boolean bool)
{
try
{
ConnectionManager.getCurrentConnection().setAutoCommit(bool);
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
转载于:https://blog.51cto.com/liumm/294255