package com.qiaoba.common.database.utils;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.exceptions.ServiceException;

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

/**
 * JdbcUtil
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
public class JdbcUtil {

    /**
     * 检查数据源是否可以连接
     *
     * @param driver   数据库驱动
     * @param url      url
     * @param username 用户名
     * @param password 密码
     * @return true = 是
     */
    public static boolean checkConnect(String driver, String url, String username, String password) {
        Connection conn = null;
        try {
            try {
                Class.forName(driver);
                //建立连接
                conn = DriverManager.getConnection(url, username, password);
                return true;
            } catch (SQLException e) {
                return false;
            }
        } catch (Exception e) {
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Connection getConnection(String driver, String url, String username, String password) {
        Connection conn = null;
        try {
            Class.forName(driver);
            //建立连接
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (Exception e) {
            throw new ServiceException(StrUtil.format("数据源连接失败,错误: {}", e.getMessage()));
        }
    }
}
