简体   繁体   English

Java Derby SQL查询语句使用变量

[英]Java Derby SQL query statement using variables

    String val = searchText.getText();

    System.out.println(val);
    System.out.println(tmp);
    if (tmp == "properShippingName") {
        try {

            String sql = "SELECT SDS_NUMBER, PRODUCT_NAME, PROPER_SHIPPING_NAME FROM APP.MASTER WHERE PROPER_SHIPPING_NAME LIKE ?";
            pst = conn.prepareStatement(sql);

            pst.setString(1, val);
            rs = pst.executeQuery();
            // System.out.println("rs");

            jTable1.setModel(DbUtils.resultSetToTableModel(rs));

        } catch (Exception e) {
            e.printStackTrace(System.out);
            JOptionPane.showMessageDialog(null, e);
        }

My first question is I want to run the query using like %val%. 我的第一个问题是我想使用%val%来运行查询。 I want the query to return anything close to what the user inputs into the "searchText" text field. 我希望查询返回与用户在“ searchText”文本字段中输入的内容接近的任何内容。 I can not seem to figure out how to get it to recognize the variable and still execute the LIKE constraint. 我似乎无法弄清楚如何使它识别变量并仍然执行LIKE约束。

Any help would be greatly appreciated! 任何帮助将不胜感激!

I do have a second question on the same topic but slightly different problem so I will post another thread. 我在同一主题上有第二个问题,但问题略有不同,因此我将发布另一个主题。

You have to include the percent in your setString method call. 您必须在setString方法调用中包含百分比。

pst.setString(1, "%" + val + "%");

Now the like - statement works with this wildcards. 现在like-语句可与此通配符一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM