使用占位符在postgresql中搜索

时间:2015-04-01 13:26:15

标签: java postgresql

我想在表中搜索包含子字符串的标题(在我的例子中,子字符串是传递给getBookForTitle方法的标题)。问题是它没有返回任何东西。

public void getBookForTitle(String title) {
            PreparedStatement stm = null;
            ResultSet rs = null;
    try {
                stm = connection.prepareStatement("Select * from books where name like '%?%'; ");
                rs = stm.executeQuery();
                while (rs.next()) {
                    System.out.print(rs.getInt(1));
                    System.out.print(": ");
                    System.out.print(rs.getString(1));
                    System.out.println(rs.getBoolean(3));
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }

        }

2 个答案:

答案 0 :(得分:1)

您永远不会将值绑定到占位符。占位符也不应包含%符号和单引号。

看起来像是:

stm = connection.prepareStatement("Select * from books where name like ? ");
stm.setString(1,"%"+your_string+"%")

答案 1 :(得分:0)

您错过了为预准备语句参数提供的值:

stm = connection.prepareStatement("Select * from books where name like ? ");
stm.setString(1,"%" + lookup + "%")
rs = stm.executeQuery();

请注意,绑定参数时应设置%字符,而不是在语句本身中设置。

请参阅:http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html#supply_values_ps