Mysql数据源提交

This commit is contained in:
liangdaliang
2025-02-20 18:07:24 +08:00
parent 3bca275ca8
commit 4ddca7f72c
3 changed files with 62 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
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
* @Descriptionmysql执行器
* @date 2025-02-20 17:05
*/
public class MySQLExecutor {
/**
* 执行 SQL 查询,并将结果转换为 List<Map<String, Object>>
*
* @param sql SQL 查询语句(已包含参数值)
* @param url 数据库 URL
* @param user 数据库用户名
* @param password 数据库密码
* @return 查询结果(每行数据为一个 Map
*/
public static List<Map<String, Object>> executeQuery(String sql, String url, String user, String password) {
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 + " 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);
row.put(columnName, columnValue);
}
result.add(row);
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return result;
}
}