簡體   English   中英

java jdbc如何正確將數據添加到JsonObject

[英]java jdbc how can I properly add data into JsonObject

我正在使用JDBC從MySQL數據庫中檢索2條記錄,並將它們轉換為JsonObject,但是代碼無法正常工作,例如:我得到了這個結果

{"locations":[{"city":"OrlandoOrlando","state":"WVFL"}]}

代替

{"locations":[{"city":"Orlando","state":"WV"},{"city":"Orlando","state":"WV"}]}

我知道自己的狀態,但似乎可以找到糾正方法,這是我的代碼

String city="";
String state="";
try {
   JSONObject jo = new JSONObject();
   Connection conn = DB.getConnection();
   ResultSet rs;
  PreparedStatement ps = conn.prepareStatement("select city,state from zips limit 2");
   rs = ps.executeQuery();
   while (rs.next()) {
// The problem is in this area the: city+ and state+
       city+= rs.getString("city");
       state+= rs.getString("state");
   }
   jo.put("city",city);
   jo.put("state", state);
   JSONArray ja = new JSONArray();
   ja.put(jo);
   JSONObject mainObj = new JSONObject();
   mainObj.put("locations", ja);

問題出在上面的city +和state +字符串中,但是如果我這樣做

while (rs.next()) {
   city= rs.getString("city");
   state= rs.getString("state");
 }

它修復了所有問題,但只返回了1條記錄,而不是2條,看起來像這樣

{"locations":[{"city":"Orlando","state":"WV"}]}

任何建議都很好。

我已經進行了更改,以通過SQL輸出構建JSONArray。

JSONObject jo = new JSONObject();
Connection conn = DB.getConnection();
ResultSet rs;
PreparedStatement ps = conn.prepareStatement("select city,state from zips limit 2");
rs = ps.executeQuery();
JSONArray ja = new JSONArray();
while (rs.next()) {
    jo.put("city", rs.getString("city"));
    jo.put("state", rs.getString("state"));
    ja.put(jo);
}

JSONObject mainObj = new JSONObject();
mainObj.put("locations", ja);
JSONObject jo = null;
Connection conn = DB.getConnection();
ResultSet rs;
PreparedStatement ps = conn.prepareStatement("select city,state from zips limit 2");
rs = ps.executeQuery();
JSONArray ja = new JSONArray();
while (rs.next()) {
    jo = new JSONObject();
    jo.put("city", rs.getString("city"));
    jo.put("state", rs.getString("state"));
    ja.put(jo);
}
JSONObject mainObj = new JSONObject();
mainObj.put("locations", ja);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM