连接池类的使用
使用DBCP
package com.datasource;
import java.sql.Connection;
import java.sql.Statement;
import org.apache.commons.dbcp.BasicDataSource;
public class DBConn
{
private static DBConn dc;
private Connection conn = null;
private Statement stmt = null;
private DBConn()
{
}
public static DBConn instance()
{
if (dc == null)
{
dc = new DBConn();
}
return dc;
}
public Statement openStmt()
{
if (stmt == null)
{
conn = getConn();
try
{
stmt = conn.createStatement();
}
catch (Exception e)
{
System.err.println("创建Statement异常: " + e.getMessage());
}
}
return stmt;
}
public void closeStmt()
{
if (stmt != null)
{
try
{
stmt.close();
}
catch (Exception e)
{
System.err.println("Statement关闭异常");
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (Exception e)
{
System.err.println("数据库关闭异常");
}
}
}
private Connection getConn()
{
if (conn == null)
{
try
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/j2ee");
ds.setUsername("root");
ds.setPassword("123456");
conn = ds.getConnection();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return conn;
}
}
使用C3P0:
package com.datasource;
import java.sql.Connection;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBConnC3p0
{
private static DBConnC3p0 dc;
private Connection conn = null;
private Statement stmt = null;
private DBConnC3p0()
{
}
public static DBConnC3p0 instance()
{
if (dc == null)
{
dc = new DBConnC3p0();
}
return dc;
}
public Statement openStmt()
{
if (stmt == null)
{
conn = getConn();
try
{
stmt = conn.createStatement();
}
catch (Exception e)
{
System.err.println("创建Statement异常: " + e.getMessage());
}
}
return stmt;
}
public void closeStmt()
{
if (stmt != null)
{
try
{
stmt.close();
}
catch (Exception e)
{
System.err.println("Statement关闭异常");
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (Exception e)
{
System.err.println("数据库关闭异常");
}
}
}
public Connection getConn()
{
if (conn == null)
{
try
{
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/j2ee");
ds.setUser("root");
ds.setPassword("32147");
ds.setMaxPoolSize(40);
ds.setMinPoolSize(2);
ds.setMaxStatements(180);
conn = ds.getConnection();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return conn;
}
}