使用PreparedStatement的无效列索引

使用PreparedStatement的无效列索引

本文介绍了使用PreparedStatement的无效列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查询相同的数据.但是即使文档中所说的索引从1开始,preparedStatement也会引发有关错误索引的SQLException.

I am trying to query same data.But the preparedStatement thrown an SQLException about wrong indexing even though the index start from 1 as the documentation said.

这是函数:

public List<Paper1> search(String keyword) throws NotConnectedException {

    List<Paper1> papers = new ArrayList<>();

    try {
        PreparedStatement searchKeyword =
        connection.prepareStatement("SELECT title, registered FROM paper "
        + "WHERE title LIKE '%?%'");
        searchKeyword.setString(1, keyword);
        ResultSet rs = searchKeyword.executeQuery();

        while (rs.next()) {
            Paper1 p = new Paper1();
            p.setTitle(rs.getString("title"));
            p.setRegistered(rs.getDate("registered").toLocalDate());
            papers.add(p);
        }
        return papers;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

SQLException表示,错误的行是

The SQLException said, the wrong line is the

searchKeyword.setString(1, keyword);

由于列索引错误

推荐答案

您的问号占位符位于单引号内,因此它被视为文字字符-根本不是占位符.解析该语句时,'%?%'只是一个字符串,看不到绑定变量,因此无法设置绑定变量-没有变量,因此没有索引为1的变量.

Your question-mark place holder is inside single quotes, so it's being seen as a literal character - and not a place holder at all. When the statement is parsed the '%?%' is just a string and no bind variable is seen, so no bind variable can be set - there are no variables, so no variable with index 1.

您可以使用串联来解决此问题:

You can use concatenation to fix this:

    PreparedStatement searchKeyword =
    connection.prepareStatement("SELECT title, registered FROM paper "
    + "WHERE title LIKE '%' || ? || '%'");

这篇关于使用PreparedStatement的无效列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:51