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

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

    import org.apache.commons.dbcp.BasicDataSource;

    public class DbUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    private static int initSize;
    private static int maxActive;
    private static BasicDataSource ds;

    static{
    ds=new BasicDataSource();
    Properties cfg=new Properties();
    try {
    InputStream in=DbUtils.class.getClassLoader().
    getResourceAsStream("db.properties");
    cfg.load(in);
    //初始化参数
    driver=cfg.getProperty("jdbc.driver");
    url=cfg.getProperty("jdbc.url");
    user=cfg.getProperty("jdbc.user");
    password=cfg.getProperty("jdbc.password");
    initSize=Integer.parseInt(cfg.getProperty("initSize"));
    maxActive=Integer.parseInt(cfg.getProperty("maxActive"));
    in.close();
    //初始化连接池
    ds.setDriverClassName(driver);
    ds.setUrl(url);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setInitialSize(initSize);
    ds.setMaxActive(maxActive);

    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    }
    }

    public static Connection getConnection(){
    try {
    Connection conn=ds.getConnection();
    return conn;
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    }

    }

    public static void close(Connection conn){
    if(conn!=null){
    try {
    conn.close();
    } catch (Exception e) {

    }
    }
    }
    public static void rollback(Connection conn){
    if (conn!=null) {
    try {
    conn.rollback();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    }

  • 相关阅读:
    判断两个对象是否相同
    参数的修饰符
    异常处理
    类型转换
    值类型和引用类型
    抽象方法实现计算器
    静态
    多态
    访问修饰符
    面向对象三大特性
  • 原文地址:https://www.cnblogs.com/Bighua123/p/7567383.html
Copyright © 2011-2022 走看看