![](/img/trans.png)
[英]How do I put in the values (of different data types) from two HashMaps with the same keys into a new third HashMap?
[英]How do i put data from an SQL Database to a Hashmap?
我需要從 SQL 數據庫中檢索數據並將其放入 hashmap,我對如何做到這一點有點迷茫,尤其是對於我給定的數據類型,如果有人可以幫助並向我解釋這個過程,那就太好了,這里是在我的代碼下面:
public void load (Path p) throws DataLoadingException {
try {
String pathString = p.toString();
Connection c = DriverManager.getConnection("jdbc:sqlite:"+pathString);
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("select * from PassengerNumbers;");
while (rs.next()) {
LocalDate date = LocalDate.parse(rs.getString("Date"));
int flightnumber = Integer.parseInt(rs.getString("FlightNumber"));
int loadestimate = Integer.parseInt(rs.getString("LoadEstimate"));
}
rs.close();
c.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SqlDb 中的數據如下所示:
(PK TEXT) (PK INTEGER) (INTEGER)
Date FlightNumber LoadEstimate
2020-07-01 618 124
Hashmap 包含鍵值對並將每個唯一鍵映射到一個值。
根據 SQL 數據庫信息,您提供的表具有復合主鍵,換句話說,您的主鍵由兩列(TEXT 類型的日期和 INTEGER 類型的航班號)組成。
如您所知,主鍵具有唯一值,以幫助您在查詢表中的數據時進行區分。 因此,您應該在 hashmap 中存儲表的主鍵作為鍵。
現在,由於您的主鍵由兩列組成,並且它們的值的組合可以幫助您識別唯一性,因此您可以創建一個數組或列表並將日期和 * flightNumber * 存儲在那里。 然后,您將將此數組/列表作為鍵添加到 hashmap 中,並將所需字段的 rest(在我們的示例中為 INTEGER 類型的loadEstimate )作為其值。
上面的代碼應該是這樣的:
HashMap<ArrayList<Object>, int> myMap = new HashMap<>(); //Create your hashmap
while (rs.next()) {
LocalDate date = LocalDate.parse(rs.getString("Date"));
int flightnumber = Integer.parseInt(rs.getString("FlightNumber"));
int loadestimate = Integer.parseInt(rs.getString("LoadEstimate"));
//Create array resembling the primary key
ArrayList<Object> mapKey = new ArrayList<>();
mapKey.add(date);
mapKey.add(new Integer(flightnumber));
//Store to Map the key and the value
myMap.put(mapKey, loadestimate);
}
//then do sth with the hashmap
請注意,我創建了一個類型為 Object 的通用對象數組,以便能夠存儲不同類型的對象。 這是可能的,因為它們都是 class Object 的子類。
此外,Java 中的安全模式是在您完成后在 finally 塊中關閉您的 ResultSet、Statement 和 Connection(按此順序)。 因此,在 catch 塊之后添加這個 finally 塊:
finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { s.close(); } catch (Exception e) { /* ignored */ }
try { c.close(); } catch (Exception e) { /* ignored */ }
}
我的建議是創建一個 Flight class,您可以在其中將所有三個值存儲為屬性,這樣您就可以將三個值存儲在一個地方。 這使得可以將每個 Flight object 存儲在 Hashmap<Integer,Flight> 中。 類似於下面的代碼。
HashMap<Integer,Flight> hashMap = new HashMap<Integer,Flight>;
Integer key = 0;
while (rs.next()) {
LocalDate date = LocalDate.parse(rs.getString("Date"));
int flightnumber = Integer.parseInt(rs.getString("FlightNumber"));
int loadestimate = Integer.parseInt(rs.getString("LoadEstimate"));
Flight newFlight = new Flight(date,flightnumber,loadestimate);
hashMap.put(key, newFlight);
key++;
}
通過這種方式,您可以通過遍歷 hashmap 來訪問所有數據,因為您知道它的大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.