小编典典

java.sql.SQLException:参数索引超出范围(1>参数数量,为0)。在使用PreparedStatement时

sql

在Java / MariaDb中使用prepareStatement,如以下函数所示

public ArrayList<String> findPath(String roomName) throws SQLException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException
{
    ArrayList<String> path = new ArrayList<String>(); 
    connection = getConnection();
    String queryPattern = "SELECT `Livello_1`, `Livello_2`, `Livello_3`, `Livello_4` FROM Camera WHERE Camera.Nome = '?'";
    PreparedStatement queryStatement = connection.prepareStatement(queryPattern);
    queryStatement.setString(1, roomName);
    ResultSet rs = queryStatement.executeQuery();
    if(rs.next())
    {
        for(int i = 0; i < 3; i++)
        {
            path.add(rs.getString(i));
        }
    }
    return path;
}

我收到错误消息:

java.sql.SQLException:参数索引超出范围(1>参数数量,为0)。

错误行号指向行

queryStatement.setString(1, roomName);

阅读 200

收藏
2021-03-10

共1个答案

小编典典

正如评论中提到的,您应该删除?中的引号。

另外,在中rs.getString(i)i应为正。从1开始循环计数。

总结一下:

public ArrayList<String> findPath(String roomName) throws SQLException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException
{
    ArrayList<String> path = new ArrayList<String>(); 
    connection = getConnection();
    String queryPattern = "SELECT Livello_1, Livello_2, Livello_3, Livello_4 FROM Camera WHERE Camera.Nome = ?";
    PreparedStatement queryStatement = connection.prepareStatement(queryPattern);
    queryStatement.setString(1, roomName);
    ResultSet rs = queryStatement.executeQuery();
    if(rs.next())
    {
        for(int i = 1; i < 4; i++)
        {
            path.add(rs.getString(i));
        }
    }
    return path;
}
2021-03-10