简体   繁体   中英

Storing resultset in an arraylist Java

My program queries a MySQL database on the band and CD band, and return the query as a resultset. I am trying to store the resultset of the CD table query into an arraylist so the Title and Year of each CD is stored and then added to the current Band through addCD(CD cd). My Band class has an arraylist of CD objects, and my CD objects has a String for the title, and int for the year.

You can select TITLE and YEAR values from CD table in a single SQL query as below. YEAR would then become available at index(2) of the resultset . Use the wrapper class Integer to convert the YEAR string to an int .

rs = st.executeQuery("SELECT TITLE, YEAR FROM CD WHERE BAND_ID = " + i + ";");

// notice the name change below
Band band = new Band(name); // or, call this "b" to avoid name conflict

// Get the title of each CD for the current band
while (rs.next()) {
    band.addCD(
        new CD(rs.getString(1), Integer.parseInt(rs.getString(2))); // int year;
}

// Add a new band to the arraylist
bandList.add(band); // Added "List" to the name

I've taken the liberty of changing a few names. Basically, calling a list of bands, bandList or even bands makes the purpose of the variable more clearer than calling it a band (singular).

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