BaseDao数据库连接样板

发布于:2023-01-04 ⋅ 阅读:(201) ⋅ 点赞:(0)

private static String driverClass = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/本地数据库名?useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
    private String user = "root";
    private String password = "root";

    //加载数据库驱动
    static{
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接
    protected Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    //关闭数据库连接
    public void closeConnection(ResultSet resultSet, Statement statement,Connection connection){
        try{
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到