Mugiwara0705
Mugiwara0705

Reputation: 23

SQL error in java code "Column count doesn't match value count at row 1"

I have a problem with my program. When I try to write to my database (in MySQL) I get this error "Column count doesn't match value count at row 1"

This is my code:

public void registreerNieuwSpelbord(String spelnaam, String mapcode) {
    try (Connection connectie = DriverManager.getConnection(Connectie.JDBC_URL)) {
        Statement stmt = connectie.createStatement();
        String schrijfSpelbordWeg = "INSERT INTO spelbord(Mapcode, spel_Spelnaam) values('" + mapcode + "," + spelnaam + "')";
        stmt.executeUpdate(schrijfSpelbordWeg);
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

note: there is also a 3th column with an ID that automatically gives a number

Upvotes: 2

Views: 65

Answers (2)

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

You should always use a PreparedStatement and bind variables when dealing with SQL that takes input parameters. This way, you're eliminating the chance of SQL injection, allowing the DB to re-use/cache your query and sparing yourself from hunting down bugs that are caused by missing a quote around a parameter.

Here's a refactored version that uses parameterized SQL:

public void registreerNieuwSpelbord(String spelnaam, String mapcode) {

    String sql = "INSERT INTO spelbord(Mapcode, spel_Spelnaam) values(?, ?)";

    try (Connection connectie = DriverManager.getConnection(Connectie.JDBC_URL);
            PreparedStatement ps = connectie.prepareStatement(sql);) {

        ps.setString(1, mapcode);
        ps.setString(2, spelnaam);
        ps.executeUpdate();

    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

Upvotes: 0

Jason Byrne
Jason Byrne

Reputation: 1619

You have two columns listed in the insert, but only one value.

Try this:

String schrijfSpelbordWeg = "INSERT INTO spelbord(Mapcode, spel_Spelnaam) values('" + mapcode + "','" + spelnaam + "')";

Upvotes: 1

Related Questions