java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). While using PreparedStatement

java, jdbc, sql

Solution

As was mentioned in the comment, you should remove the quotes from the ?.

In addition, in `rs.getString(i)`, `i` should be positive. Start the count of the loop from 1.

To summarize:

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;
}

Problem

Using preparedStatement in Java/MariaDb as in the following function ``` 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; } ``` I obtain the error message: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). and the error line number points to line ``` queryStatement.setString(1, roomName); ```

Original source

Related problems