【问题标题】:Create a JSON file by reading a mySQL table in java通过在 java 中读取 mySQL 表来创建 JSON 文件
【发布时间】:2017-01-17 13:48:36
【问题描述】:

我想选择我的数据表并将其内容存储在JSON 文件中。但是我的JSON 文件内容多次只有我表的最后一行。你能帮我找出我错在哪里吗?谢谢...

这是我的java代码的一部分:

 JSONObject obj = new JSONObject();
 JSONArray array = new JSONArray();

 try {
    conn = DriverManager.getConnection(url, utilisateur, motDePasse);
    preparedStatement = conn.prepareStatement("SELECT idUser, emailUser, motPassUser FROM utilisateur;");
    result = preparedStatement.executeQuery("SELECT idUser, emailUser, motPassUser FROM utilisateur;");

    obj = new JSONObject();
    array = new JSONArray();

    while (result.next()) {
        obj.put("id", result.getInt("idUser"));
        obj.put("email", result.getString("emailUser"));
        obj.put("password", result.getString("motPassUser"));
        array.add(obj);
    }

    try {
        FileWriter file = new FileWriter("user.json");
        file.write(((JSONArray) array).toJSONString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
} catch (SQLException e) {

} finally {
    if (result != null) {
        try {
            result.close();
        } catch (SQLException ignore) {
        }
    }
    if (preparedStatement != null) {
        try {
            preparedStatement.close();
        } catch (SQLException ignore) {
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException ignore) {
        }
    }
}

这是我的 JSON 文件的输出:

[{"id":3,"email":"tindongabou@gmail.com","password":"ludovic1992"},
{"id":3,"email":"tindongabou@gmail.com","password":"ludovic1992"},
{"id":3,"email":"tindongabou@gmail.com","password":"ludovic1992"}]

它只包含我表格的最后一行...

【问题讨论】:

    标签: java mysql json select jdbc


    【解决方案1】:

    在while循环中创建JSON对象

    while (result.next()) {
    
    obj = new JSONObject();
    
            obj.put("id", result.getInt("idUser"));
    
            obj.put("email", result.getString("emailUser"));
    
            obj.put("password", result.getString("motPassUser"));
    
            array.add(obj);
        }
    

    【讨论】:

      【解决方案2】:

      将此行放在您的 while 循环中 -

      obj = new JSONObject();
      

      【讨论】:

      • 如果它有效,请您接受它作为答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多