zoukankan      html  css  js  c++  java
  • DBCP连接池

    方法一:

    package DBCPUtils;

    import java.util.List;
    import java.util.Properties;

    import javax.sql.DataSource;

    import org.apache.commons.dbcp.BasicDataSourceFactory;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.ArrayListHandler;

    public class DBCPUtils {

    public static void main(String[] args) {
    try {
    // 读取配置文件
    Properties properties = new Properties();
    properties.load(DBCPUtils.class.getClassLoader()
    .getResourceAsStream("jdbc.properties"));
    // 从连接池中获取连接对象
    DataSource dataSource = BasicDataSourceFactory
    .createDataSource(properties);

    String sql = "select * from emp";
    QueryRunner qr = new QueryRunner(dataSource);
    List<Object[]> list = qr.query(sql, new ArrayListHandler());
    for (Object[] objects : list) {
    for (Object object : objects) {
    System.out.print(object + " ");
    }
    System.out.println();
    }


    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    方法二:

    package DBUtils;

    import java.io.InputStream;
    import java.util.Properties;

    import javax.sql.DataSource;

    import org.apache.commons.dbcp.BasicDataSource;

    public class DBUtils {
    private static String DriverClass;
    private static String url;
    private static String username;
    private static String password;
    private static BasicDataSource dataSource = new BasicDataSource();
    static {
    loadRead();
    dataSource.setDriverClassName(DriverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    }

    private static void loadRead() {
    try {
    InputStream in = DBUtils.class.getClassLoader()
    .getResourceAsStream("jdbc.properties");
    Properties properties = new Properties();
    properties.load(in);
    DriverClass = properties.getProperty("DriverClass");
    url = properties.getProperty("url");
    username = properties.getProperty("username");
    password = properties.getProperty("password");
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public static DataSource getDataSource(){
    return dataSource;
    }

    }

  • 相关阅读:
    剑指offer--50.滑动窗口的最大值
    剑指offer--49.矩阵中的路径
    剑指offer--48.机器人的运动范围
    剑指offer--47.数据流中的中位数
    剑指offer--46.字符流中第一个不重复的字符
    剑指offer--45.二叉树的深度
    剑指offer--44.两个链表的第一个公共结点
    剑指offer--43.连续子数组的最大和
    海盗分宝石问题
    C++数组名退化指针实例
  • 原文地址:https://www.cnblogs.com/czb2580/p/6228011.html
Copyright © 2011-2022 走看看