単一のHashMapオブジェクトを使用して、SQLクエリから取得した複数のレコードを格納できます。
データベース接続を設定してクエリを実行した後、ResultSetオブジェクトを実行し、モデルクラスを使用してオブジェクトを作成し、IPをキーとしてHashMapに追加します。以下のコードは、それを行う方法の例を示します。
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;
}
}
}
キー(IP)を使用して、オブジェクトから結果を取得することができますが、またにArraListまたはいくつかの他のデータ構造を使用することができますあなたの記録を保存しますが、あなたはそれらをどのように通過するかを変更する必要があります。
私はこれがあなたを助けてくれることを願っています。
DBテーブルの内容を 'Map'に保存する方法を聞いていますか?現在のデータアクセスコードはどのように見えますか? –