2

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

2
  • You're missing the closing single-quotes (') in your query in that middle comma section (","): INSERT INTO spelbord(Mapcode, spel_Spelnaam) values('" + mapcode + "','" + spelnaam + "') Commented Apr 26, 2015 at 20:21
  • 1
    Note that you wouldn't have had this problem if you were using a PreparedStatement, which is what you should be using every time you're inputting parameters into SQL. This way you can avoid SQL injection problems and do not need to worry about (valid) parameters containing special characters like '. Commented Apr 26, 2015 at 20:34

2 Answers 2

1

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 + "')";
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't mention in my answer above that the reason is you missed two single quotes that should have been there, which you'll see in the code above.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.