注:需要的jar包:
commons-dbcp-1.3.jar
commons-pool-1.5.6.jar
配置文件
dbcpconfig.properties
package cn.dbcp;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import com.mysql.jdbc.PreparedStatement;
//dbcp连接池
public class DBCPUtils {
private static DataSource ds;
static {
try {
// 通过类加载器获取到properties文件中的数据。
InputStream in = DBCPUtils.class.getClassLoader()
.getResourceAsStream("cn/dbcp/dbcpconfig.properties");
Properties pro = new Properties();
pro.load(in);
// 关键代码
ds = BasicDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获得connection
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 关闭资源,还回拿出来的资源
public static void closeJdbc(Connection conn, ResultSet st,
PreparedStatement ps) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试类
package cn.dbcp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
public class Test {
private static Connection conn;
private static Statement st;
private static PreparedStatement ps;
public static void add() throws Exception{
conn = DBCPUtils.getConnection();
System.out.println(conn);
DBCPUtils.closeJdbc(conn, null, null);
}
public static void main(String[] args) throws Exception {
add();
}
}
原文地址:http://blog.csdn.net/u013032887/article/details/36902747