我似乎无法弄清楚为什么会出现此异常:SQLException:参数索引超出范围(1 > 参数数量,即 0)。
我的 mysql 连接器版本是5.1.29.这可能是这个版本的问题,还是我没有正确设置查询?
抓取:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes"
+ "(bikename, country_of_origin, cost) VALUES"
+ "(?,?,?)";
try {
statement.setString(1, (String)winners_combo_box.getSelectedItem());
statement.setString(2, winner_fields[0].getText());
statement.setFloat(3, Float.parseFloat(winner_fields[1].getSelectedText()));
statement.executeUpdate(query);
} catch(SQLException e1) {
e1.printStackTrace();
}
}
最佳答案
您没有为该方法中的statement
赋值,并且您正在使用 overload of executeUpdate
from Statement
...而不是 PreparedStatement
中的无参数。
我怀疑您实际上想使用 Connection.prepareStatement
分配该语句:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes"
+ "(bikename, country_of_origin, cost) VALUES"
+ "(?,?,?)";
// TODO: Connection management?
PreparedStatement statement = conn.prepareStatement(query);
try {
statement.setString(1, (String)winners_combo_box.getSelectedItem());
statement.setString(2, winner_fields[0].getText());
statement.setFloat(3, Float.parseFloat(winner_fields[1].getSelectedText()));
statement.executeUpdate();
} catch(SQLException e1) {
e1.printStackTrace();
// TODO: Don't just pretend it worked...
} finally {
statement.close();
}
}
基本上,您不应该尝试重复使用语句。就我个人而言,我也尝试不重用连接,使用连接池来处理底层连接的重用,但这是另一回事。
关于java - 将字段值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873205/