首页 > 编程 > Java > 正文

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

2019-11-26 11:04:42
字体:
来源:转载
供稿:网友

demo需求:

实现jdbc结合dpcp连接池的封装(以oracle数据库为例)并实现简单地查找demo主要技术:
(1)Properties类加载.properties的方式(2)dpcp连接池建立数据库连接的方式(3)查询数据的方式(4)静态代码块的使用,分离驱动的加载和连接信息的载入,整个服务器生命周期只执行一次

demo所用jar包:

classes12.jarcommons-dbcp-1.4.jarcommons-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<String> 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连接池的封装实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表