package com.test.common.utils;

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

/**
 * @author liangdaliang
 * @Description：mysql执行器
 * @date 2025-02-20 17:05
 */
public class MySQLExecutor {


    /**
     * 执行 SQL 查询，并将结果转换为 List<Map<String, Object>>
     *
     * @param sql SQL 查询语句（已包含参数值）
     * @param url 数据库 URL
     * @param user 数据库用户名
     * @param password 数据库密码
     * @param columnNameList 所有列名集合
     * @return 查询结果（每行数据为一个 Map）
     */
    public static List<Map<String, Object>> executeQuery(String sql, String url, String user, String password, List<String> columnNameList) {
        List<Map<String, Object>> result = new ArrayList<>();
        try (Connection connection = DriverManager.getConnection(url, user, password);
             Statement statement = connection.createStatement()) {
            // 执行查询，限制最大100行
            try (ResultSet resultSet = statement.executeQuery(sql.replaceAll(";", "") + " LIMIT 100")) {
                // 获取结果集的元数据
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                // 遍历结果集
                while (resultSet.next()) {
                    Map<String, Object> row = new HashMap<>();
                    for (int i = 1; i <= columnCount; i++) {
                        // 获取字段名和字段值
                        String columnName = metaData.getColumnLabel(i);
                        Object columnValue = resultSet.getObject(i);
                        int columnType = metaData.getColumnType(i);
                        if (columnType == Types.BIT) {
                            row.put(columnName, resultSet.getInt(columnName));
                        } else {
                            row.put(columnName, columnValue);
                        }
                        if (i == 1) {
                            columnNameList.add(columnName);
                        }
                    }
                    result.add(row);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

//    public static void main(String[] args) {
//        String url = "jdbc:mysql://47.103.142.5:3306/cmcf-test";
//        List<String> columnNameList = new ArrayList<>();
//        List<Map<String, Object>> resultMapList = MySQLExecutor.executeQuery("select * from test_task t", url, "test", "Test123@", columnNameList);
//        ObjectMapper objectMapper = new ObjectMapper();
//        try {
//            String result = objectMapper.writeValueAsString(resultMapList);
//            System.out.println(result);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//    }
}
