【问题标题】:How can I set dynamically prepared query statement in Java?如何在 Java 中设置动态准备的查询语句?
【发布时间】:2015-11-25 10:39:59
【问题描述】:

我有一个 jtable。我从 mysql 数据库运行数据。我使用带有准备好的语句的查询:

"select * from customer where city=? and region=? and price>?"
 pst.setString(1,"rome")
 pst.setstring(2,"italy")
 pst.setdouble(3,"1500")

我的问题是有一次我只需要一个参数(例如城市)。 我问你我每次查询时都会改变或者我可以设置参数的动态数量??

谢谢

【问题讨论】:

  • 您需要单独查询这些情况。

标签: java mysql prepared-statement


【解决方案1】:

(我认为将它们分成单独的查询是一个更好的解决方案,但如果你想这样做,也许这样的事情可以帮助你)

我曾经写过这样的东西

public ArrayList<User> searchUsers(HashMap userProperties)
{
    ArrayList<User> foundUsers = new ArrayList<User>();

    String searchString = "select * from chatusers where ";
    int addedProps = 0;
    if (userProperties.get("username") != null && !userProperties.get("username").equals(""))
    {
        searchString += "nickname like '%" + userProperties.get("username") + "%'";
        addedProps++;
    }
    if (userProperties.get("firstname") != null && !userProperties.get("firstname").equals(""))
    {
        if (addedProps > 0)
            searchString += " AND ";
        searchString += "voornaam like '%" + userProperties.get("firstname") + "%'";
        addedProps++;
    }
    if (userProperties.get("lastname") != null && !userProperties.get("lastname").equals(""))
    {
        if (addedProps > 0)
            searchString += " AND ";
        searchString += "naam like '%" + userProperties.get("lastname") + "%'";
    }
....

当然,您必须将“userProperties.get("prop"). 更改为“?”(我知道我需要使用preparedStatements,这只是为了在我们看到preparedStatements 之前在大学里做一些愚蠢的事情。

此外,我会以类似的方式继续最终实际绑定变量。 (跟踪您在哪里添加了哪个变量,在哪个索引处,因为 if 语句而知道)。

【讨论】:

  • 像这样动态构建查询是一个非常糟糕的主意,除非确实没有更好的选择,否则不应尝试。
  • 我完全同意你的看法。我在帖子开头提到了它,但如果 OP 坚持,这是有可能的。 ^^ 但是,我不会再这样做了;-)
猜你喜欢
  • 2014-07-11
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多