package com.hs.common.utils;

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

public class JdbcUtil {

    /**
     * 获取数据库连接
     *
     * @param driver   数据库驱动类
     * @param url      数据库链接
     * @param username 用户名
     * @param password 密码
     * @return Connection
     */
    public static Connection getConnection(String driver, String url, String username, String password) {
        Connection conn = null;
        try {
            Class.forName(driver);
            System.out.println(">>>>>>>>>>>加载驱动成功!!!<<<<<<<<<<<");
            conn = DriverManager.getConnection(url, username, password);
            System.out.println(">>>>>>>>>>>数据库连接成功!!!<<<<<<<<<");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println(">>>>>>>>>>>连接数据库失败!!!<<<<<<<<<");
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 获取PreparedStatement
     *
     * @param conn   数据库连接
     * @param sql    执行语句
     * @param params 参数
     * @return PreparedStatement
     * @throws SQLException SQL异常
     */
    public static PreparedStatement getPreparedStatement(Connection conn, String sql, List params) throws SQLException {
        PreparedStatement pstmt = conn.prepareStatement(sql);
        if (null != params && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }
        }
        return pstmt;
    }

    /**
     * 开启事务
     *
     * @param connection 数据库连接
     */
    public static void startTransaction(Connection connection) throws SQLException {
        if (null != connection) {
            connection.setAutoCommit(false);
        }
    }

    /**
     * 提交
     *
     * @param connection 数据库连接
     * @throws SQLException SQLException
     */
    public static void commit(Connection connection) throws SQLException {
        if (null != connection) {
            connection.commit();
            connection.setAutoCommit(true);
        }
    }

    /**
     * 回滚
     *
     * @param connection 数据库连接
     * @throws SQLException SQLException
     */
    public static void rollback(Connection connection) throws SQLException {
        if (null != connection) {
            connection.rollback();
            connection.setAutoCommit(true);
        }
    }

    /**
     * 关闭连接
     *
     * @param connection 数据库连接
     * @param statement  Statement
     * @param resultSet  结果集
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }

        if (statement != null) {
            statement.close();
        }

        if (connection != null && connection.getAutoCommit()) {
            connection.close();
        }
    }
}
