1

I want to select my data's table and store its content inside a JSON file. But my JSON file content only the last row of my table multiple time. Can you help me to identify where i'm wrong? Thank you...

Here is a part of my java code :

 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) {
        }
    }
}

And this the output of my JSON file :

[{"id":3,"email":"[email protected]","password":"ludovic1992"},
{"id":3,"email":"[email protected]","password":"ludovic1992"},
{"id":3,"email":"[email protected]","password":"ludovic1992"}]

It contents only the last row of my table...

2 Answers 2

1

create JSON object inside while loop as

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Put this line inside your while loop -

obj = new JSONObject();

1 Comment

can you please accept it as answer if it is working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.