【问题标题】:When injecting into a sql query using java, gets an error使用 java 注入 sql 查询时,出现错误
【发布时间】:2012-10-22 21:04:33
【问题描述】:
public ArrayList<Message> searchMessages(String word) throws DaoException{
    ArrayList<Message> messages = new ArrayList<>();
            Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        con = getConnection();

        //String query = "SELECT * FROM messages WHERE text LIKE %?% order by date";
        String query = "SELECT * FROM messages WHERE text LIKE '%?%'";
        ps = con.prepareStatement(query);
        ps.setString(1,word);
        rs = ps.executeQuery();

        while (rs.next()) {
            int messageId = rs.getInt("messageId");
            String text = rs.getString("text");

            String date = rs.getString("date");
            int memberId2 = rs.getInt("memberId");
            Message m = new Message(messageId,text,date,memberId2);
            messages.add(m);

            //Company c = new Company(companyId, symbol, companyName, sharePrice, high, low);
            //companies.add(c);
        }
    } catch (SQLException e) {
        throw new DaoException("searchMessages(): " + e.getMessage());
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                freeConnection(con);
            }
        } catch (SQLException e) {
            throw new DaoException("searchMessages(): " + e.getMessage());
        }
    }

    return messages;

}

首先解释一下代码。它只是搜索消息表及其文本字段以查找提供的任何内容。我使用准备好的语句将其插入查询并运行它。无论我提供什么字符串给出这个错误

oow_package.DaoException: searchMessages(): Parameter index out of range (1 > number of parameters, which is 0).

不知道为什么它一点也不工作。将不胜感激。

【问题讨论】:

  • 如果您找到了正确答案,请查看旁边的标记,将其标记为已接受的答案。

标签: java mysql


【解决方案1】:

您不能在准备好的语句中使用这样的参数。查询应该是

SELECT * FROM messages WHERE text LIKE ?

你应该使用

ps.setString(1, "%" + word + "%");

【讨论】:

  • 这是正确的,它已修复,非常感谢。现在将更新帖子,并在允许时将您的帖子标记为正确答案。非常感谢
【解决方案2】:

我不是专家,但我会说你准备好的语句没有参数被识别,你仍然插入一个(单词)......也许问题来自 % 符号?

编辑:同意上面的人......似乎合法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2020-09-27
    • 2012-09-29
    相关资源
    最近更新 更多