【发布时间】:2015-07-01 01:58:40
【问题描述】:
我正在使用 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"}]}
任何建议都会很棒..
【问题讨论】:
-
如何在循环之前创建 JSONArray 并在循环中添加提取的值? JSONArray ja = new JSONArray();while (rs.next()) { city= rs.getString("city"); state= rs.getString("state");jo.put("city",city); jo.put("state", state);ja.put(jo); }
-
嘿,我刚试过,但结果只给了我 {"locations":[{"city":"Orlando","state":"WV"}]}。
-
您的数据库中有 FL 条目吗?你能检查 3 条不同状态的记录吗?
-
是的,我在我的记录中的状态列下有一个带有 FL,WV 的条目,是的,我可以。我正在尝试附加数据的新方法。
标签: java jdbc jsonobject