JDBC+DBCP连接池操作Mysql数据库

工具类的抽取:

public class JDBCUtil {
    private static BasicDataSource dataSource = new BasicDataSource() ; //创建数据源
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    

//静态代码块
    static{
        readConfig();

        //数据源设置参数
        dataSource.setDriverClassName(driverClass);
        dataSource.setPassword(password);
        dataSource.setUsername(username);
        dataSource.setUrl(url);
    }
    
    //读配置文件
    private static void readConfig(){

        //1.加载找properties文件输入流
        InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("product.properties");
        Properties pro = new Properties();
        try {

           //2.加载输入流
            pro.load(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //读取配置文件中的参数
        driverClass = pro.getProperty("driverClass");
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
    }
    
    public static DataSource getDataSource(){
        return dataSource;
    }

//获取数据库连接池对象

public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/jinchunzhao123/article/details/81159759