开源数据源 DBCP
package com.itheima.jdbc;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
// BasicDataSource source = new BasicDataSource();
// source.setDriverClassName("com.mysql.jdbc.Driver");
// source.setUrl("jdbc:mysql:///day11");
// source.setUsername("root");
// source.setPassword("root");
try {
Properties prop = new Properties();
prop.load(new FileReader("dbcp.properties"));
BasicDataSourceFactory factory = new BasicDataSourceFactory();
DataSource source = factory.createDataSource(prop);
conn = source.getConnection();
ps = conn.prepareStatement("select * from account");
rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs = null;
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ps = null;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
}
}
Properties文件内容:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///day11
user=root
password=root
开源数据库连接池C3P0
ComboPooledDataSource dataSource = new ComboPooledDataSource();
ComboPooledDataSource dataSource = new ComboPooledDataSource("mySoruce");
com.mysql.jdbc.Driver
jdbc:mysql:///Day12
root
root
com.mysql.jdbc.Driver
jdbc:mysql:///Day12
root
root
driverClass
jdbcUrl
user
password
acquireIncrement:当连接池中已经没有连接时,连接池自动获取连接时一次获取的连接个数。
initialPoolSize:连接池初始化时,获取连接的个数。
maxPoolSize:连接池可以保有的最大的连接的数量。
maxIdleTime:当连接空闲多久时释放连接。如果该时间值设置问为0,表示从不释放连接。
minPoolSize:连接池应该保有的最小的连接的数量。