将字段值插入数据库

时间:2014-04-04 21:19:50

标签: java mysql

我似乎无法弄清楚为什么我会收到此异常:SQLException: Parameter index out of range (1 > number of parameters, which is 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();
    }
}

1 个答案:

答案 0 :(得分:1)

您没有为该方法中的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();
    }
}

基本上,您不应该尝试重用语句。我个人也尝试不重用连接,使用连接池来处理底层连接的重用,但这是另一回事。