number of parameters, which is 0)"的准备语句参数错误-6ren"> number of parameters, which is 0)"的准备语句参数错误-我正在尝试将变量插入数据库。 这是我的代码: public static void main(String[] args) throws SQLException { Connection c-6ren">
gpt4 book ai didi

java - "JAVA parameter index out of range (1 > number of parameters, which is 0)"的准备语句参数错误

转载 作者:行者123 更新时间:2023-12-02 01:00:16 25 4
gpt4 key购买 nike

我正在尝试将变量插入数据库。

这是我的代码:

public static void main(String[] args) throws SQLException {
Connection connection =null;
DBhelper helper = new DBhelper();
PreparedStatement statement = null;
ResultSet resultSet;
try{
connection= helper.getConnection();

System.out.println("baglantı olustu");

String sql = "INSERT INTO pandemi(toplamvirus) VALUES ('?') ";
statement = connection.prepareStatement(sql);
statement.setInt(1,2);
statement.executeUpdate(sql);
int result = statement.executeUpdate();
}
catch (SQLException exception){
helper.showErrorMessage(exception);
}
finally {
statement.close();
connection.close();
}



//String sql = "UPDATE pandemi SET toplamvirus='ff' ";





}

错误是:

baglantı olustu
Error: Parameter index out of range (1 > number of parameters, which is 0).
Error code : 0

数据库是:https://prnt.sc/rile7q

最佳答案

将参数序数和值传递给setInt

您错误地使用了 PreparedStatement::setInt方法。第一个参数是序数(在 Javadoc 中错误地记录为索引)。因此第一个占位符是#1,第二个占位符是#2,依此类推。您只有一个 ? 占位符。或者您是否试图传递一个值 2 来插入数据库?你的问题不清楚。

使用裸

此外,您需要删除 prepared statement? 占位符周围的单引号。 。使用 '?' 意味着您希望将包含问号的单字符字符串插入到数据库中。使用单引号后,SQL 语句中就没有占位符了。所以你的 setInt 方法将会失败。如果使用裸露的 ?,问号将被识别为占位符。

顺便说一句,我建议养成使用 SQL 语句终止符(分号)的习惯。

String sql = "INSERT INTO pandemi ( toplamvirus ) VALUES ( ? ) ; ";

有关详细信息,请参阅 another Answer of mine使用 H2 数据库引擎的完整示例应用程序演示了在准备好的语句中使用占位符插入INSERT

关于java - "JAVA parameter index out of range (1 > number of parameters, which is 0)"的准备语句参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60746540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com