java.sql.SQLException: 参数索引超出范围(1 > 参数数量,为 0)。使用 PreparedStatement 时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20362660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). While using PreparedStatement
提问by Germano Massullo
Using preparedStatement in Java/MariaDb as in the following function
在 Java/MariaDb 中使用 PreparedStatement 如下函数
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).
java.sql.SQLException: 参数索引超出范围(1 > 参数数量,为 0)。
and the error line number points to line
并且错误行号指向行
queryStatement.setString(1, roomName);
采纳答案by Eran
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.
此外,在rs.getString(i)
,i
应该是积极的。从 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;
}