【常见的数据库连接池】
所有的数据库连接池实现都要指定sun定义的连接池接口-javax.sql.DataSource
1.DBCP
DBCP连接池是tomcat默认支持的连接池,在tomcat的lib目录下可看见tomcat-dbcp.jar;
如果没有的话,须执行引入commons-dbcp-1.2.2.jar和commons-pool.jar 早期版本可能还需引入commons-collection.jar
简单入门实例:
public class DBCP {
public static void getConnection() throws Exception {
// 1. 获取连接池对象
BasicDataSource source = new BasicDataSource();
// 2. 设置连接池对象
source.setDriverClassName("com.mysql.jdbc.Driver");
source.setUrl("jdbc:mysql:///dbutils");
source.setUsername("root");
source.setPassword("root");
source.setDefaultAutoCommit(true);
source.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
source.setInitialSize(10);
source.setMaxActive(5);
source.setMaxIdle(10);
source.setMinIdle(0);
source.setMaxWait(5000);
Connection conn = source.getConnection();
String sql = "insert into test(name) values(?)";
PreparedStatement state = conn.prepareStatement(sql);
state.setString(1, "scoield");
state.executeUpdate();
state.close();
System.out.println("插入数据成功");
}
public static void main(String[] args) throws Exception {
getConnection();
}
}
上面的代码发现设置番茄花园下载参数的方法过多,得一个个的设置,过于繁琐!
配置文件方式代码实现:
dbcp.properties
username=root
password=root
url=jdbc\:mysql\:///dbutils
driverClassName=com.mysql.jdbc.Driver
defaultAutoCommit=true
defaultTransactionIsolation=REPEATABLE_READ
initialSize=10
maxActive=5
maxIdle=5
minIdle=0
maxWait=5000
java代码:
public class DBCP {
public static void getConnection2() throws Exception{
Properties prop = new Properties();
InputStream url = DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
prop.load(url);
BasicDataSource source = (BasicDataSource) BasicDataSourceFactory.createDataSource(prop);
Connection conn = source.getConnection();
String sql = "insert into test(name) values(?)";
PreparedStatement state = conn.prepareStatement(sql);
state.setString(1, "scoield1");
state.executeUpdate();
state.close();
System.out.println("插入数据成功");
}
public static void main(String[] args) throws Exception {
getConnection2();
}
}