第一种方式,无配置
public static void main(String[] args) {
//DBCP第一种方式
BasicDataSource source = new BasicDataSource();
source.setDriverClassName("oracle.jdbc.OracleDriver");
source.setUrl("jdbc:oracle:thin:@172.18.9.24:1521:orcl");
source.setUsername("scott");
source.setPassword("tiger");
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = source.getConnection();
String sql = "select * from emp20";
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
第二种方式,配置实现
public static void main(String[] args) {
//DBCP第二种方式
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
Properties properties = new Properties();
FileInputStream in = new FileInputStream("dbcpconfig.properties");
properties.load(in);
DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
conn = dataSource.getConnection();
String sql = "select * from emp20";
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
DBCP配置文件,dbcpconfig.properties
#数据库配置
driverClassName=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@172.18.9.24:1521:orcl
username=scott
password=tiger
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_COMMITTED