Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sql

jdbc

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);
like image 376
Germano Massullo Avatar asked Oct 02 '22 06:10

Germano Massullo


1 Answers

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;
}
like image 67
Eran Avatar answered Oct 08 '22 20:10

Eran