我正在尝试从 MySQL 数据库接收数据,并保存其中包含多个变量的所有行,并将它们放入一个变量中。
我的数据库:
############################################
#192.168.1.1 | Instance1 | 19.988 | 0 | 20 #
############################################
############################################
#192.168.1.2 | Instance2 | 19.878 | 1 | 19 #
############################################
and so on...
从该数据库中,我收到条目/行中包含的数据(唯一键是 IP 地址 [第一个条目])
现在我的目标是将所有这些数据存储在一个变量中,以便我可以列出所有实例并向它们显示相应的数据。
<小时/>问题:
是否有一种方法可以将这些数据存储在一个变量中(类似于具有更多行的 HashMap),或者是否有更好的方法来存储数据?
最佳答案
您可以使用单个 HashMap 对象来存储来自 SQL 查询的多条记录。
设置数据库连接并执行查询后,只需遍历 ResultSet 对象,使用模型类创建一个对象,然后使用 IP 作为键将其添加到 HashMap 中。下面的代码显示了如何执行此操作的示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_database", "db_user", "db_password");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");
HashMap<String, DBRecord> results = new HashMap<>();
while (resultSet.next()) {
results.put(resultSet.getString(1), new DBRecord(
resultSet.getString(1),
resultSet.getString(2),
resultSet.getFloat(3),
resultSet.getInt(4),
resultSet.getInt(5)
));
}
connection.close();
printHashMap(results);
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
public static void printHashMap(HashMap<String, DBRecord> records) {
for (Map.Entry pair : records.entrySet()) {
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
public static class DBRecord {
private String ip, instance;
private double firstValue;
private int secondValue, thirdValue;
public DBRecord(String ip, String instance, double firstValue, int secondValue, int thirdValue) {
this.ip = ip;
this.instance = instance;
this.firstValue = firstValue;
this.secondValue = secondValue;
this.thirdValue = thirdValue;
}
//Gets and sets...
@Override
public String toString() {
return ip + " | " + instance + " | " + firstValue + " | " + secondValue + " | " + thirdValue;
}
}
}
使用 HashMap,您可以使用键 (IP) 从对象中检索结果,但您也可以使用 ArraList 或其他一些数据结构来存储您的记录,尽管您需要更改查看它们的方式。
希望这对您有帮助。
关于java - 将排序后的多个数据放入一个变量中(就像 HashMap 只是具有更多行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46455524/