欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

数据库连接池工具类

程序员文章站 2022-12-20 18:53:18
package model.dao;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.IOException;import java.io.InputStream;import java.sql.*;import java.util.Properties;public class BaseDao { private static Stri...
package model.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    private static DataSource dataSource;

    static
    {
        //读取资源文件,获取连接参数
        Properties properties=new Properties();
        //通过类加载器读取资源文件
        InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //获取连接池
    public static DataSource getDataSource()
    {
        return dataSource;
    }

    //获取数据库连接
    public static Connection getConnection() throws SQLException {
        
        return dataSource.getConnection();
    }

    //释放资源
    public static void close(Statement statement,Connection connection)
    {
       close(null,statement,connection);
    }
//重载方法
    public static void close(ResultSet resultSet,Statement statement, Connection connection)
    {
        if(resultSet!=null)
        {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement!=null)
        {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null)
        {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}

本文地址:https://blog.csdn.net/qq_44627732/article/details/109646554

相关标签: Java web