TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
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();
}
}
}
本文出自 51CTO.COM技术博客 |
|