简体   繁体   中英

How do I insert MySQL Table data into an JSONArray?

I'm trying to get some data from a MySQL table and insert this data into an JSONArray.

Below my Code:

public static JSONArray get_inactive_bookings(String username) {
        JSONArray array = new JSONArray();
        JSONObject obj = new JSONObject();
        Connection conn = null;
        ResultSet rs = null;
        int index = 0;
        int user_id = Users.get_user_id(username);
        String sql = "select * from bookings where user_id =" + user_id + 
                " and Effettiva_Restituzione is not null";
        try {
            conn = Utilities.connect();
            Statement st = conn.createStatement();
            rs = st.executeQuery(sql);
            //This is where I think problem shows up
            while (rs.next()) {

                obj.put("Booking_ID", rs.getInt("booking_id"));
                obj.put("Book_Title", Books.get_title(rs.getInt("book_id")));
                obj.put("Booking_Date", rs.getString("Data_Prenotazione"));
                obj.put("Return_Date", rs.getString("Data_Restituzione"));
                array.add(index, obj);
                index++;
            }
        } catch (SQLException ecc) {
            System.out.println("ERROR: " + ecc.getMessage());
        } finally {
            Utilities.disconnect(conn);
        }
        return array;
    }

In my table I have two occurrences once sql query is executed but in the resulting array I get two times the last occurrence in the Table. I guess it's while's fault. Do you guys know how to get both occurrences in the JSONArray? Thank you

In the first iteration, the key-values are added firstly. But after the first iteration, you are overriding the mapped values for each keys in the object. Because, you add the same object multiple times overriding its entries. You must create a new jsonObject with each iteration. So the

JSONObject obj = new JSONObject();

must be in the while loop. like

public static JSONArray get_inactive_bookings(String username) {
    JSONArray array = new JSONArray();
    //JSONObject obj = new JSONObject(); -> this line must be in while loop
    Connection conn = null;
    ResultSet rs = null;
    int index = 0;
    int user_id = Users.get_user_id(username);
    String sql = "select * from bookings where user_id =" + user_id + 
            " and Effettiva_Restituzione is not null";
    try {
        conn = Utilities.connect();
        Statement st = conn.createStatement();
        rs = st.executeQuery(sql);
        //This is where I think problem shows up
        while (rs.next()) {
            JSONObject obj = new JSONObject(); // moved to here
            obj.put("Booking_ID", rs.getInt("booking_id"));
            obj.put("Book_Title", Books.get_title(rs.getInt("book_id")));
            obj.put("Booking_Date", rs.getString("Data_Prenotazione"));
            obj.put("Return_Date", rs.getString("Data_Restituzione"));
            array.add(index, obj);
            index++;
        }
    } catch (SQLException ecc) {
        System.out.println("ERROR: " + ecc.getMessage());
    } finally {
        Utilities.disconnect(conn);
    }
    return array;
}

Moreover, you don't need to keep 'index' separately to specify place of the element to be added. It is already added by default to the end of the array. So, it is better to add element like: array.add(obj); if the new element will be added to the end of the array.

You need to move your object instantiation into the loop, like this:

public static JSONArray get_inactive_bookings(String username) {
        JSONArray array = new JSONArray();
        Connection conn = null;
        ResultSet rs = null;
        int index = 0;
        int user_id = Users.get_user_id(username);
        String sql = "select * from bookings where user_id =" + user_id + 
                " and Effettiva_Restituzione is not null";
        try {
            conn = Utilities.connect();
            Statement st = conn.createStatement();
            rs = st.executeQuery(sql);
            //This is where I think problem shows up
            while (rs.next()) {
                JSONObject obj = new JSONObject();

                obj.put("Booking_ID", rs.getInt("booking_id"));
                obj.put("Book_Title", Books.get_title(rs.getInt("book_id")));
                obj.put("Booking_Date", rs.getString("Data_Prenotazione"));
                obj.put("Return_Date", rs.getString("Data_Restituzione"));
                array.add(index, obj);
                index++;
            }
        } catch (SQLException ecc) {
            System.out.println("ERROR: " + ecc.getMessage());
        } finally {
            Utilities.disconnect(conn);
        }
        return array;
    }

对于要放入数组中的每个元素,您都使用相同的JSONObject(相同的引用),因此只需在一个循环中覆盖其值即可。

JSONObject obj = new JSONObject(); //put this inside your while loop

You need create a new object in each iteration, because you are overwriting that object-

while (rs.next()) {
    JSONObject obj = new JSONObject();
    obj.put("Booking_ID", rs.getInt("booking_id"));
    obj.put("Book_Title", Books.get_title(rs.getInt("book_id")));
    obj.put("Booking_Date", rs.getString("Data_Prenotazione"));
    obj.put("Return_Date", rs.getString("Data_Restituzione"));
    array.add(index, obj);
    index++;
}

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