package backend.utils;

import java.sql.*;

public class DBHelper {
    // 数据库驱动名
    private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    /***  以下请根据实际情况修改  ****/
    private static final String IP = "kronecker.cc"; // ip地址
    private static final String PORT = "3306"; // 端口
    private static final String DB_NAME = "DataManagerSystem"; // 数据库名
    private static final String USER = "group";
    private static final String PASSWORD = "123456";
    /***  以上请根据实际情况修改  ****/
    private static final String DB_URL = String.format("jdbc:mysql://%s:%s/%s", IP, PORT, DB_NAME);
    // 单例模式写法之一
    private final static DBHelper instance;

    static {
        try {
            instance = new DBHelper();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    // 私有无参构造
    private DBHelper() throws SQLException {}
    public static DBHelper getInstance(){
        return instance;
    }
    // 1. 注册驱动
    static {
        try {
            Class.forName(JDBC_DRIVER);
            System.out.println("数据库加载成功");
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载失败: " + e.getMessage());
        }
    }
    // 2. 创建连接
    public Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
        } catch (SQLException e) {
            System.out.println("获取连接失败: " + e.getMessage());
        }
        return conn;
    }
    // 3. 关闭连接
    public void close(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            System.err.println("资源关闭失败:" + e.getMessage());
        }
    }
    public static void main(String[] args) {
        DBHelper.getInstance().getConnection();
    }
}
