带有可选参数的PreparedStatement SQL

时间:2015-08-21 08:26:57

标签: java sql sql-server-2008 prepared-statement

所以我正在创建一个搜索功能,用户可以选择输入哪些字段,并根据这些字段查询数据库,忽略未输入的字段。这是我用来尝试实现这个目的的代码:

    PreparedStatement ps = DeviceTracker.getConnection().prepareStatement("use SBK_CAPE_COOKIES SELECT * FROM \"CC_Employees\"" 
                                                                          +"WHERE EmployeeID LIKE ? AND FirstName LIKE ? AND Surname LIKE ? AND Email LIKE ? AND Region LIKE ? AND Department LIKE ?"
                                                                          ,ResultSet.TYPE_SCROLL_INSENSITIVE,  ResultSet.CONCUR_READ_ONLY);
    if (!jTextField6.getText().isEmpty()) ps.setInt(1, Integer.parseInt(jTextField6.getText()));
    else ps.setString(1, "'%'"); 
    if (!jTextField5.getText().isEmpty()) ps.setString(2, "'"+jTextField5.getText()+"'");
    else ps.setString(2, "'%'"); 
    if (!jTextField4.getText().isEmpty()) ps.setString(3, "'"+jTextField4.getText()+"'");
    else ps.setString(3, "'%'"); 
    if (!jTextField3.getText().isEmpty()) ps.setString(4, "'"+jTextField3.getText()+"'");
    else ps.setString(4, "'%'"); 
    if(!jComboBox1.getSelectedItem().equals("All")) ps.setString(5, "'"+jComboBox1.getSelectedItem().toString()+"'");
    else ps.setString(5, "'%'"); 
    if(!jComboBox2.getSelectedItem().equals("All")) ps.setString(6, "'"+jComboBox2.getSelectedItem().toString()+"'");
    else ps.setString(6, "'%'"); 
    ResultSet rs = ps.executeQuery();

每次ResultSet'rs'都为空。我做错了什么?

1 个答案:

答案 0 :(得分:2)

删除setString方法中的单引号。它们将由准备好的声明自动设置。

 PreparedStatement ps = DeviceTracker.getConnection().prepareStatement("use SBK_CAPE_COOKIES SELECT * FROM \"CC_Employees\"" 
                                                                          +"WHERE EmployeeID LIKE ? AND FirstName LIKE ? AND Surname LIKE ? AND Email LIKE ? AND Region LIKE ? AND Department LIKE ?"
                                                                          ,ResultSet.TYPE_SCROLL_INSENSITIVE,  ResultSet.CONCUR_READ_ONLY);
    if (!jTextField6.getText().isEmpty()) ps.setInt(1, Integer.parseInt(jTextField6.getText()));
    else ps.setString(1, "%"); 
    if (!jTextField5.getText().isEmpty()) ps.setString(2, jTextField5.getText());
    else ps.setString(2, "%"); 
    if (!jTextField4.getText().isEmpty()) ps.setString(3, jTextField4.getText());
    else ps.setString(3, "%"); 
    if (!jTextField3.getText().isEmpty()) ps.setString(4, jTextField3.getText());
    else ps.setString(4, "%"); 
    if(!jComboBox1.getSelectedItem().equals("All")) ps.setString(5, jComboBox1.getSelectedItem().toString());
    else ps.setString(5, "%"); 
    if(!jComboBox2.getSelectedItem().equals("All")) ps.setString(6, jComboBox2.getSelectedItem().toString());
    else ps.setString(6, "%"); 
    ResultSet rs = ps.executeQuery();

你的陈述的结果是像WHERE EmployeeID LIKE '1' AND FirstName LIKE '''firstname'''

那样的somithing

但我认为这不是你方法的好设计。您应该动态生成查询,因此只添加使用的参数。