package com.qiaoba.common.database.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.exceptions.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;

/**
 * JdbcUtil
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@Slf4j
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 {
            Class.forName(driver);
            //建立连接
            conn = DriverManager.getConnection(url, username, password);
            return true;
        } catch (Exception e) {
            log.debug(e.getMessage());
            return false;
        } finally {
            IoUtil.close(conn);
        }
    }

    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()));
        }
    }

}
