jdbc结合dpcp连接池的封装实例

网友投稿 250 2023-03-23


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(geXuD"连接池创建失败");

}

}

/**

* 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)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:c 微信接口开发教程(微信编程接口)
下一篇:elemetUi 组件
相关文章

 发表评论

暂时没有评论,来抢沙发吧~