package util;

import java.sql.*;

/**
 * @Description
 * @Author koe
 * @Data 2022/6/15 15:49
 */

public class DBUtil {
    static String url = "jdbc:mysql://localhost:3306/eatwhat?useUnicode=true&characterEcoding=utf-8";
    // 中文变？问题 ？useUnicode=true&characterEncoding=utf-8
    static String user = "root";
    static String password = "123456";

    /**
     * 加载类库  链接驱动类
     */
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 实例化数据库链接对象
     * @return
     */
    public static Connection getConnection(){
        Connection cont = null;
        try {
            cont = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return cont;
    }

    /**
     * 关闭数据库链接  释放资源
     * @param res	结果指针对象
     * @param pstmt	执行对象
     * @param cont	链接对象
     */
    public static void closeJDBC(ResultSet res, Statement pstmt, Connection cont){
        if(res != null){
            try {
                res.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(pstmt != null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(cont != null){
            try {
                cont.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
