我知道这个问题在stackoverflow上已经问过很多次了,但是我仍然无法查明我的代码为什么不起作用的确切原因。
这是查询:
String QUERY = "INSERT INTO orders (user, product_id, final_price, key_id) VALUES (?, ?, ?, ?)";
使用我在失败函数中使用的相同参数手动运行查询,效果很好。
这是PreparedStatement:
// ...more code up here...
PreparedStatement preparedStatement = connectionManager.databaseConnection.prepareStatement(QUERY);
preparedStatement.setInt(1, user_id);
preparedStatement.setInt(2, product_id);
preparedStatement.setFloat(3, _finalprice);
// ...more code down there...
preparedStatement.setInt(4, _keyid);
我得到的错误如下:
java.sql.SQLException: Parameter index out of range (0 < 1 ).
我还有其他几种使用相同技术完成的INSERT,它们都可以完美地工作,我开始认为我正在使用的mysqlconnector存在一些问题(mysql-connector-java-8.0.19)。 / p>
完整的上下文代码:
private static boolean assignProduct(int product_id, int user_id)
{
String QUERY = "INSERT INTO orders (user, product_id, final_price, key_id) VALUES (?, ?, ?, ?)";
float _finalprice = 0;
int _discount = 0;
int _keyid = 0;
if(product_id <= 0 || user_id <= 0) {return false;}
Product _p;
try {
_p = Product_utils.productByID(product_id);
if(_p != null)
{
_finalprice = _p.getPrice();
_discount = _p.getDiscount();
if(_discount > 0)
{
_finalprice = _finalprice - (_finalprice * _discount / 100);
}
}else { return false;}
PreparedStatement preparedStatement = connectionManager.databaseConnection.prepareStatement(QUERY);
preparedStatement.setInt(1, user_id);
preparedStatement.setInt(2, product_id);
preparedStatement.setFloat(3, _finalprice);
_keyid = retriveKey(product_id);
if(_keyid == 0) { return false; }
preparedStatement.setInt(4, _keyid);
if(preparedStatement.executeUpdate() == 1) {return true;} else {return false;}
} catch (SQLException e) { System.out.println(e.toString()); return false;}
}
答案 0 :(得分:0)
通过将mysql连接器升级到8.0.20来解决