Java 使用 Map 类型接收 MySQL 数据
可以使用 Java 的 JDBC API 来从 MySQL 数据库中读取数据,然后将数据存储在 Java 中的 Map 对象中。以下是一个示例代码:
import java.sql.*;
import java.util.*;
public class MySQLDataToMap {
public static void main(String[] args) {
// MySQL 连接参数
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "mypassword";
// 建立 MySQL 连接
try (Connection conn = DriverManager.getConnection(url, username, password)) {
// 创建查询语句
String sql = "SELECT id, name, age FROM mytable";
PreparedStatement stmt = conn.prepareStatement(sql);
// 执行查询
ResultSet rs = stmt.executeQuery();
// 将查询结果存储在 Map 中
Map<Integer, Map<String, Object>> resultMap = new HashMap<>();
while (rs.next()) {
int id = rs.getInt('id');
String name = rs.getString('name');
int age = rs.getInt('age');
Map<String, Object> rowMap = new HashMap<>();
rowMap.put('name', name);
rowMap.put('age', age);
resultMap.put(id, rowMap);
}
// 输出 Map 中的数据
for (Map.Entry<Integer, Map<String, Object>> entry : resultMap.entrySet()) {
int id = entry.getKey();
Map<String, Object> rowMap = entry.getValue();
String name = (String) rowMap.get('name');
int age = (int) rowMap.get('age');
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
以上代码演示了如何将 MySQL 中的数据存储在 Java 中的 Map 对象中,并输出 Map 中的数据。在此示例中,我们使用了 HashMap 来存储结果,但您也可以使用其他类型的 Map 来存储结果,例如 TreeMap 等。
原文地址: https://www.cveoy.top/t/topic/oWvp 著作权归作者所有。请勿转载和采集!