java dpcp_jdbc结合dpcp连接池的封装实例

demo需求:

实现jdbc结合dpcp连接池的封装(以oracle数据库为例)并实现简单地查找demo主要技术:

(1)Properties类加载.properties的方式

(2)dpcp连接池建立数据库连接的方式

(3)查询数据的方式

(4)静态代码块的使用,分离驱动的加载和连接信息的载入,整个服务器生命周期只执行一次

demo所用jar包:

classes12.jar

commons-dbcp-1.4.jar

commons-pool-1.5.4.jar

demo主要代码展示:

Utils.java

private static Connection conn = null;

private static BasicDataSource dataSource = new BasicDataSource();

private static Properties prop = getProperties("src/db.properties");

// 将连接池的创建放在静态代码块,保证整个服务器生命周期只执行一次,减少服务器负担

static {

try {

dataSource.setDriverClassName(prop.getProperty("driver"));

dataSource.setUrl(prop.getProperty("url"));

dataSource.setUsername(prop.getProperty("user"));

dataSource.setPassword(prop.getProperty("password"));

dataSource.setMaxActive(20);

dataSource.setInitialSize(10);

} catch (Exception e) {

System.out.println("连接池创建失败");

}

}

/**

* show 方法简介 获取数据库连接池的连接,因为已经封装,以后只需要配置db.properties,无需动这边代码

*

* @author 叶灬黎

* @return

*/

public static Connection getConnection() {

try {

conn = dataSource.getConnection();

} catch (Exception e) {

System.out.println("数据库连接失败");

}

return conn;

}

/**

* show 方法简介 读取.properties文件,这里主要服务于想将jdbc连接数据库的各项参数抽取出来

*

* @author 叶灬黎

* @param file

* 要读取的.properties文件的路径

* @return Properties类对象

*/

private static Properties getProperties(String file) {

Properties properties = new Properties();

try {

FileInputStream fis = new FileInputStream(new File(file));

properties.load(fis);

fis.close();

} catch (IOException e) {

System.out.println("加载配置文件出错");

}

return properties;

}

OneSelect.java

public static void main(String[] args) {

List names = new ArrayList<>();

try {

Connection conn = Utils.getConnection();

//创建执行引擎

Statement state = conn.createStatement();

//执行sql

String sql = "select * from emp";

ResultSet rs = state.executeQuery(sql);

while(rs.next()){

names.add(rs.getString("ename"));

}

rs.close();

state.close();

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

for(String s : names){

System.out.println(s);

}

}

db.properties(src目录下)

driver = oracle.jdbc.driver.OracleDriver

url = jdbc:oracle:thin:@127.0.0.1:1521:orcl

user = scott

password = 123456

demo资源位置:

svn://106.15.229.200/Javaweb/tinyDemo_jdbc 用户temp/密码temp)

以上这篇jdbc结合dpcp连接池的封装实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值