package com.qmth.teachcloud.eds.utils.gdpu;

import java.sql.*;
import java.util.List;

public class JdbcUtil {

    // MySQL8.0以下版本 - JDBC驱动名及数据库URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

    private String dbUrl;
    private String user;
    private String pass;

    public JdbcUtil(String dbUrl, String user, String pass) {
        this.dbUrl = dbUrl;
        this.user = user;
        this.pass = pass;
    }

    public String getDbUrl() {
        return dbUrl;
    }

    public void setDbUrl(String dbUrl) {
        this.dbUrl = dbUrl;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public <T> List<T> query(String sql, Class<T> clazz) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 注册 JDBC 驱动,加载驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接,连接数据库
            conn = DriverManager.getConnection(this.dbUrl, this.user, this.pass);
            System.out.println("数据库连接成功");

            // 执行查询
            stmt = conn.createStatement();
            System.out.println("实例化Statement对象成功");
            rs = stmt.executeQuery(sql);
            System.out.println("ResultSet对象返回成功");
            return ResultSetUtil.readList(rs, clazz);
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            // 完成后关闭
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            // 关闭资源
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
