Java / Mysql:从存储过程中获取所有结果行,而不仅仅是最后一行

时间:2017-09-04 12:22:39

标签: java mysql stored-procedures

我在mysql中有一个存储过程,返回多行。

enter image description here

我执行它的java代码是:

preparedStmt = conn.prepareCall(queryString);
            preparedStmt.setString(1, String.valueOf(patient_id));
            //System.out.print("select patient data java file 1 ");

            boolean results = preparedStmt.execute();

            int rowsAffected = 0;
            // Protects against lack of SET NOCOUNT in stored procedure
            while (results || rowsAffected != -1) {
                if (results) {
                    rs = preparedStmt.getResultSet();
                    break;
                } else {
                    rowsAffected = preparedStmt.getUpdateCount();
                }
                results = preparedStmt.getMoreResults();
            }
            int i = 0;
            obj = new JSONObject();
            while (rs.next()) {
                JSONArray alist = new JSONArray();
                alist.put(rs.getString("patient_id"));
                alist.put(rs.getString("allergy"));
                alist.put(rs.getString("allergy_description"));
                alist.put(rs.getString("allergy_onset_date"));
                alist.put(rs.getString("agent_description"));
                alist.put(rs.getString("agent"));
                alist.put(rs.getString("severity"));
                obj.put("ps_allergies", alist);
                i++;
            }
            conn.close();

最后,ps_allergies json对象仅包含查询的最后一行。这是打印输出:

["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]

我希望ps_allergies包含与

类似的内容
[["1","hydrogen peroxide","Nuts","2017-07-04","Nursing profressionals","43","Paramedical practinioners"],["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]...]

你知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

不完全知道您使用的是哪个库,但它可能与此行有关: cmake ..\..\examples\src\MyApp\ -DCMAKE_INSTALL_PREFIX=D:\Repos\install -DCMAKE_PREFIX_PATH=C:\Qt\5.8\msvc2015\lib\cmake msbuild MyApp.sln /property:Configuration=Debug msbuild MyApp.sln /property:Configuration=Release

put方法通常将指定值与映射中的指定键相关联。因为你经常覆盖你的关键词' ps_allergies'在循环中它只保留最后一个值。

您可能希望将列表/数组关联到ps_allergies,然后在此列表/数组中添加每个obj.put("ps_allergies", alist);对象。

答案 1 :(得分:0)

我找到了解决方案。而不是 put 我正在使用追加方法。

obj.append("ps_allergies", alist);

现在产生的结果是:

[["1","hydrogen peroxide","Nuts","2017-07-04","Nursing professionals","43","Paramedical practitioners"],["1","chlorhexidine","test123","2017-07-15","mobile contact","test232","pager"],["1","Resistance to unspecified antibiotic","Feb3","2017-03-02","mobile contact","test232","pager"],["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]]
相关问题