在Java中查询不起作用,但在MySQL中它工作正常,我该如何修复它?

时间:2014-10-11 09:15:35

标签: java mysql json

加入2个表我有一个奇怪的问题。在java中查询不起作用,它只打印一行重复但在MySQL查询中它工作正常。我需要将这些数据写入json文件中。我该如何解决这个问题?请帮忙。注意:要查看表格,请参阅链接:Need to join 2 tables but except some rows in another table in MySQL

这是我的代码:

 import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileWriter;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.List;
 import org.json.JSONObject;
 import org.json.simple.JSONArray;

 public class ShowData {
      public void Display(){
         try{
             DBConnect2 dc = new DBConnect2();
             PreparedStatement ps = null;
             ResultSet rs = null;
             Statement st= null;
             BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File("E:/workspace/Test/input/display.json")));
             String query5 = "SELECT DISTINCT k.source, k.target, k.frequency FROM links k "
                  + "LEFT JOIN logs g ON g.id = k.id "
                  + "WHERE  IFNULL(status, '') != 'Delete Edge' "
                  + "AND 'Bush' IN( k.source, k.target )";

             ps = dc.getCon().prepareStatement(query5);
             rs = ps.executeQuery();
             JSONObject obj = new JSONObject();
             JSONObject obj1 = new JSONObject();
             JSONArray list = new JSONArray();
             while(rs.next()){
                   obj1.put("source", rs.getString("source"));
                   obj1.put("target", rs.getString("target"));
                   obj1.put("frequency", rs.getInt("frequency"));
                   list.add(obj1);
             }
             obj.put("links", list);
             wr1.write(obj.toString() + "\n");
             wr1.flush();
             System.out.println("Done");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
     }

     public static void main(final String[] args){
          ShowData sw = new ShowData();
          sw.Display();
     }
}

1 个答案:

答案 0 :(得分:2)

问题似乎就在这里

JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
JSONArray list = new JSONArray();
while(rs.next()){
    obj1.put("source", rs.getString("source"));
    obj1.put("target", rs.getString("target"));
    obj1.put("frequency", rs.getInt("frequency"));
    list.add(obj1);
}

您只需创建一次obj1并将每行的内容写入其中。 JSONObject的行为类似于地图,如果您将新数据写入现有密钥,新数据将覆盖旧数据。因此,您的循环将反复覆盖旧数据,直到达到最后一行。因此,在此循环之后,只有最后一行的内容可用。

要解决此问题,请将obj1移至循环中:

JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
while(rs.next()) {
    final JSONObject obj1 = new JSONObject();
    obj1.put("source", rs.getString("source"));
    obj1.put("target", rs.getString("target"));
    obj1.put("frequency", rs.getInt("frequency"));
    list.add(obj1);
}

现在,您在每次迭代中创建JSONObject的新实例,将当前行的数据存储到该实例,并将此实例添加到JSONArray