package org.jeecg.modules.stm.polardb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {

    private static final String URL = "jdbc:mysql://zrch-polardb.rwlb.rds.aliyuncs.com/zrch?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC"; // 数据库 URL
    private static final String USER = "zrchtest"; // 数据库用户名
    private static final String PASSWORD = "zrchABC123"; // 数据库密码
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    // 静态代码块用于加载数据库驱动
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("MySQL JDBC Driver not found.");
        }
    }

    // 获取数据库连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {

            e.printStackTrace();
            throw new RuntimeException("Failed to connect to the database.");
        }
        return connection;
    }

    // 获取数据库连接
    public static Connection getConnection(String strUrl, String accout, String pwd) {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(strUrl, accout, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to connect to the database.");
        }
        return connection;
    }

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

    // 测试数据库连接
    public static void main(String[] args) {
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();
            System.out.println("Database connected successfully!");
        } catch (RuntimeException e) {
            System.out.println("Database connection failed!");
        } finally {
            DBUtil.closeConnection(connection);
        }
    }
}
