MysqlUtils.java 4.86 KB
package com.lhcredit.business.functionApi.utils;

import com.alibaba.fastjson.JSONObject;

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

/**
 * MySQL工具类
 */
public class MysqlUtils {

    private String url;
    private String username;
    private String password;
    private String driverClassName = "com.mysql.cj.jdbc.Driver";

    private Connection conn = null;
    private  PreparedStatement pstmt = null;
    private ResultSet rs = null;


    public static MysqlUtils ofZd(){
        MysqlUtils mysqlUtils = new MysqlUtils();
        mysqlUtils.init("103.110.132.64",63015,"ent_spider","root","Lianhe@123456");
        return mysqlUtils;
    }

    /**
     * 初始化MySQL连接参数
     *
     * @param host     主机地址
     * @param port     端口号
     * @param database 数据库名
     * @param username 用户名
     * @param password 密码
     */
    public void init(String host, int port, String database, String username, String password) {
        this.url = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8";
        this.username = username;
        this.password = password;
        try {
            this.conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("找不到MySQL驱动类: " + driverClassName, e);
        }
    }

    /**
     * 根据SQL语句查询List列表
     *
     * @param sql SQL查询语句
     * @return 查询结果列表,每个元素是一个Map,key为列名,value为列值
     */
    public List<JSONObject> queryList(String sql) {
        return queryList(sql, new Object[0]);
    }

    /**
     * 根据带参数的SQL语句查询List列表
     *
     * @param sql    SQL查询语句
     * @param params SQL参数
     * @return 查询结果列表,每个元素是一个Map,key为列名,value为列值
     */
    public List<JSONObject> queryList(String sql, Object... params) {
        List<JSONObject> result = new ArrayList<>();
        try {
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            rs = pstmt.executeQuery();
            // 获取结果集元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            // 遍历结果集
            while (rs.next()) {
                JSONObject row = new JSONObject();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                result.add(row);
            }
        } catch (SQLException e) {
            throw new RuntimeException("执行SQL查询出错: " + sql, e);
        } finally {
            // 关闭资源
//            closeResource(rs, pstmt, conn);
        }

        return result;
    }

    /**
     * 执行更新操作(INSERT、UPDATE、DELETE)
     *
     * @param sql    SQL语句
     * @param params SQL参数
     * @return 影响的行数
     */
    public int executeUpdate(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
            pstmt = conn.prepareStatement(sql);

            // 设置参数
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }

            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("执行SQL更新出错: " + sql, e);
        } finally {
            // 关闭资源
//            closeResource(null, pstmt, conn);
        }
    }

    /**
     * 关闭数据库资源
     *

     */
    public void closeResource() {
        if (this.rs != null) {
            try {
                this.rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (this.pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}