Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get in to JSON all the rows from sql query in JAVA

I got the next code. I think I just need to make a little change but I don't know what. The code only returns the last row but I want to see all the rows in response. If I declare a LIMIT 10 then I want to get 10 results in response.

What should I change?

Thank you.

    @RequestMapping(value="/url/results/", method=RequestMethod.GET)
    public JsonResponse getResults() throws SQLException {

        Connection connection = ConnSingle.getInstance().getConnection(env);
        String selectSql = "SELECT * FROM Lib.Table WHERE YEARS=10 LIMIT 10";

        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(selectSql);


        JSONArray json = new JSONArray();
        ResultSetMetaData rsmd = rs.getMetaData();
        JSONObject obj = new JSONObject();

        System.out.println(rsmd);

        while(rs.next()) {
            int numColumns = rsmd.getColumnCount();
            for (int i=1; i<=numColumns; i++) {
                String column_name = rsmd.getColumnName(i);
                obj.put(column_name, rs.getObject(column_name));
            }
        }

        rs.close();
        statement.close();
        connection.close();

        return new JsonResponse(obj);
    }
like image 973
FranzSif Avatar asked May 07 '26 23:05

FranzSif


1 Answers

@jaydip is right (he's beaten me by few minutes). Here is an example... You are pushing all the results in the same obj object. To display all the results you have to push "obj" into an array like this:

JSONArray objects = new JSONArray();
while(rs.next()) {
            int numColumns = rsmd.getColumnCount();
            for (int i=1; i<=numColumns; i++) {
                String column_name = rsmd.getColumnName(i);
                obj.put(column_name, rs.getObject(column_name));
                objects.add(obj);
            }
        }
rs.close();
        statement.close();
        connection.close();

        return new JsonResponse(objects);
like image 62
gmcontessa Avatar answered May 10 '26 12:05

gmcontessa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!