其他分享
首页 > 其他分享> > jdbc中Druid的JDBCUtils类

jdbc中Druid的JDBCUtils类

作者:互联网

JDBCUtils类


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//Druid的封装工具类
public class JDBCUntils {
    private static DataSource dataSource;

    static {
        //读取配置文件
        try {
            Properties properties = new Properties();
            properties.load(JDBCUntils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    //返回数据库连接池对象
    public static DataSource getDataSource() {
        return dataSource;
    }

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

    //重载个释放资源的方法
    public static void close(Connection connection, Statement statement) {
        close(connection,statement,null);
    }
}


druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///db1
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

标签:jdbc,java,throwables,Druid,JDBCUtils,static,close,import,properties
来源: https://www.cnblogs.com/codegzy/p/14731896.html