【问题标题】:select statement where condition returns multiple rows条件返回多行的选择语句
【发布时间】:2013-07-03 19:21:41
【问题描述】:

我正在尝试从相同 where 条件返回的多行中获取所有结果:

public static String getResult(String mycondition)
   {    
      ResultSet rsData = sql.RunSelect("select col1 from my_table where con ='"+myCondition+"'");
      if (rsData.next())
      {
         String result = rsData,getString("col1");
      }
   }

请注意,有一个 id 列可以区分这些行。 jsp 页面中的显示应该为返回的每一行创建文本字段。 有什么想法吗?

【问题讨论】:

    标签: java sql jsp


    【解决方案1】:

    您可以返回List<String> 或使用字符将多个字符串分隔在一个String 中。 IMO最好返回List<String>

    public static List<String> getResult(String mycondition) {
        List<String> results = new ArrayList<String>();
        ResultSet rsData = sql.RunSelect("select col1 from my_table where con='"
            +myCondition+"'");
        while (rsData.next()) {
            results.add(rsData.getString("col1"));
        }
        return results;
    }
    

    另外,这种方法容易出现SQL Injection。请注意,您的参数应与查询分开发送。也许您可以改进您的sql.RunSelect 方法以使用PreparedStatement 而不是Statement。这是代码骨架的基本示例:

    public ResultSet runSelect(String query, Object ... params) {
        //assumes you already have your Connection
        PreparedStatement pstmt = con.prepareStatement(query);
        int i = 1;
        for(Object param : params) {
            pstmt.setObject(i++, param);
        }
        return pstmt.executeQuery();
    }
    

    所以现在你可以将你的方法修改为

    public static List<String> getResult(String mycondition) {
        List<String> results = new ArrayList<String>();
        //using the new runSelect method
        ResultSet rsData = sql.runSelect(
            "select col1 from my_table where con=?", mycondition);
        while (rsData.next()) {
            results.add(rsData.getString("col1"));
        }
        return results;
    }
    

    【讨论】:

    • @jlordo 我知道这个笑话(无聊时再读一遍)对不起,刚刚更新了答案。顺便说一句,我只是尊重当前 OP 的代码。
    【解决方案2】:

    你应该使用while循环而不是if循环

    而不是 - if (rsData.next())

    使用 - while (rsData.next())

    如果您希望代码安全,尽管@Luiggi Mendoza 的答案是最好的

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 2016-10-31
      • 2012-12-12
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      相关资源
      最近更新 更多