theGrayFox
theGrayFox

Reputation: 931

Inserting field values into database

I can't seem to figure out why I'm getting this exception: SQLException: Parameter index out of range (1 > number of parameters, which is 0). My mysql connector version is 5.1.29. Is this possible a problem with this version, or am I not properly setting up the query?

Scratch:

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();
    }
}

Upvotes: 0

Views: 61

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

You're not assigning a value to statement in that method, and you're using the overload of executeUpdate from Statement... rather than the parameterless one in PreparedStatement.

I suspect you actually want to assign the statement using 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();
    }
}

You shouldn't be trying to reuse a statement, basically. Personally I'd try not to reuse a connection, either, using connection pooling to handle reuse of the underlying connection, but that's a different matter.

Upvotes: 1

Related Questions