5

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);
4
  • 2
    Remove the quotes from '?'. And stop using ` for your column names, they are not necessary. Commented Dec 3, 2013 at 22:06
  • Doing that I obtain java.sql.SQLException: Column Index out of range, 0 < 1. Commented Dec 3, 2013 at 22:07
  • 2
    '?' counts as a literal questionmark, not a placeholder for paramters. Commented Dec 3, 2013 at 22:09
  • 1
    @Caterpillar Indices start at 1, not 0. Commented Dec 3, 2013 at 22:10

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great solution for me too, I never saw anywhere that these sorts of SQL methods were not zero-indexed. Had the same problem setting prepared statement params from a for loop starting at 0. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.