简体   繁体   中英

How do i put data from an SQL Database to a Hashmap?

i need to retrieve data from an SQL database and put it in a hashmap, i'am a bit lost about how to do that especially with my given data types, if anyone can help and explain to me the process it would be great, here's below my code:

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();
    }

}

Here's what the data looks like in the SqlDb:

(PK TEXT)             (PK INTEGER)                     (INTEGER)
   Date                FlightNumber                   LoadEstimate
2020-07-01               618                              124   

A Hashmap contains key-value pairs and maps each unique key to a value.

According to the SQL database info you have provided your table has a composite primary key , in other words your primary key consists of two columns (a date of type TEXT and a flightNumber of type INTEGER).

As you know a primary key has unique values in order to help you make distinctions when querying data in a table. So, you should store in your hashmap as a key the primary key of your table.

Now, since your primary key consists of two columns and it's the combination of their values that helps you identify uniqueness, you can create an array or a list and store there the date and the * flightNumber*. Then, you will add to your hashmap this array/list as a key and the rest of the fields you want (in our case the loadEstimate of type INTEGER) as its value.

The above in code should be something like this:

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

Notice that I create an array of generic objects of type Object in order to be able to store objects of different kind. This is possible, since they both subclasses of the class Object.

Also, the safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them. So, after the catch block add this finally block:

finally {
    try { rs.close(); } catch (Exception e) { /* ignored */ }
    try { s.close(); } catch (Exception e) { /* ignored */ }
    try { c.close(); } catch (Exception e) { /* ignored */ }
}

My suggestion is to create a Flight class, in which you can store all the three values as attributes, in that way you would be able to store the three values in one place. This makes it possible to store each Flight object in a Hashmap<Integer,Flight>. Something like the code below.

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++;
}

In this way you can access all data by itterating through the hashmap, since you know the size of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM