【问题标题】:working with variable number of parameters in a preparedStatement在preparedStatement中使用可变数量的参数
【发布时间】:2012-09-30 10:31:45
【问题描述】:

我正在为我的应用程序创建一个搜索表单。
用户在其中选择应用于过滤数据的字段。
数字字段是可变的,所以我不知道 SQL 查询的 where 子句中应该有多少 ?
如何在 where 子句中使用 preparedStatement 和可变数量的条件?

谢谢

【问题讨论】:

    标签: java jdbc prepared-statement


    【解决方案1】:

    如果您想在 where 子句中添加可变数量的条件,请使用 StringBuilder(如果是多线程环境,则为 StringBuffer)和运行时间,具体取决于您的条件连接/附加到您的字符串。

    喜欢

    StringBuilder query = new StringBuilder("Select id, name from Student ");
    
    
    if(args >0)
    {
        query.append(" where "); //and add more args.
    

    然后通过将此查询转换为字符串来创建预准备语句

    PrepareStatement(query.toString());
    

    【讨论】:

      【解决方案2】:

      PrepardStatements 不支持可变数量的条件。一些框架的作用是将每个 PreparedStatement 缓存在 Map 中,其中键是查询。

      所以每次要运行查询时,都需要构建字符串来创建 PreparedStatement,检查地图中是否有它(并重用它)或创建一个新的,然后将其添加到地图中。

      【讨论】:

        猜你喜欢
        • 2015-08-10
        • 2011-12-02
        • 2016-06-16
        • 1970-01-01
        • 1970-01-01
        • 2012-10-06
        • 1970-01-01
        • 2018-04-28
        • 2013-10-21
        相关资源
        最近更新 更多