如何写个JavaBean实现数据库的共享连接?高手看过来
刚开始学java,发现很多书上写的数据库连接bean都是生成一个新进程,这样一来用户一多迟早会把服务器的资源耗尽的,可以用tomcat的连接池,可是我不知道改怎么做???
给个例子!谢谢了
问题点数:50、回复次数:1Top
1 楼108041217(josso)回复于 2005-08-02 17:46:19 得分 50
public class DBConnection {
private static DataSource ds;
private Connection conn;
private static Log log=LogFactory.getLog(DBConnection.class.getName());
static
{
try
{
Context initCtx = new javax.naming.InitialContext();
ds =(DataSource)initCtx.lookup(HttpParams.getString(Constants.DATASOURCE));
}
catch (NamingException e)
{
log.error(e.getMessage());
}
}
private DBConnection()
{
try
{
conn=ds.getConnection();
}
catch(Exception exp )
{
log.error(exp.getMessage());
}
}
public synchronized static DBConnection getInstance()
{
return new DBConnection();
}
public Connection getConnection()
{
Connection dbcn = null;
try
{
dbcn = ds.getConnection();
}
catch(Exception exp )
{
log.error(exp.getMessage());
if (dbcn !=null)
try
{
dbcn.close();
dbcn = null;
}
catch(SQLException SQLExp)
{
log.error(SQLExp.getMessage());
}
}
return dbcn;
}
public void Close()
{
try
{
conn.close();
}
catch(SQLException ex)
{
log.error("db close is error!");
}
}
public ResultSet executeQuery(String sql)
{
Statement stmt;
ResultSet rst;
rst = null;
try
{
stmt=conn.createStatement();
rst = stmt.executeQuery(sql);
}
catch(SQLException ex)
{
log.error("Query error :"+sql);
}
return rst;
}
public void RollBackTransaction()
{
try
{
conn.rollback();
}
catch(SQLException ex)
{
log.error("RollBack Transaction error");
}
}
public void BeginTransaction()
{
try
{
conn.setAutoCommit(false);
}
catch(SQLException ex)
{
log.error("Begin Transaction error");
}
}
public void CommitTransaction()
{
try
{
conn.commit();
}
catch(SQLException ex)
{
log.error("commit Transaction error");
}
}
public void executeUpdate(String sql) throws SQLException
{
Statement stmt;
ResultSet rst;
try
{
stmt=conn.createStatement();
stmt.executeUpdate(sql);
stmt.close();
}
catch(SQLException ex)
{
log.error("Update error:"+sql);
throw ex;
}
}
}Top




