简体   繁体   中英

“Column count doesn't match value count at row 1” error in program

I am inserting values into a database but get a "column count doesnt match value count value at row1" error.

try {
    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection(connectionURL, "root", "root");
    String sql = "insert into login(username,password) values(?,?)";
    PreparedStatement pst = connection.prepareStatement(sql);
    pst.setString(1, username);
    pst.setString(2, password);

    int numRowsChanged = pst.executeUpdate();
    out.println(" Data has been submitted ");

    pst.close();
} catch (ClassNotFoundException e) {
    out.println("Couldn't load database driver: " + e.getMessage());
} catch (SQLException e) {
    out.println("SQLException caught: " + e.getMessage());
} catch (Exception e) {
    out.println(e);
} finally {
    try {
        if (connection != null)
            connection.close();
    } catch (SQLException ignored) {
        out.println(ignored);
    }
}

This my table in MySql database:

           +----------+-------------+------+-----+---------+-------+
           | Field    | Type        | Null | Key | Default | Extra |
           +----------+-------------+------+-----+---------+-------+
           | username | varchar(20) | YES  |     | NULL    |       |
           | password | varchar(15) | YES  |     | NULL    |       |
           +----------+-------------+------+-----+---------+-------+

Why am I getting this error? Is there something wrong in my code? Please help me.......

也许在sql String中列的名称不正确。

The error is itself erroneous probably, as everything looks fine. Maybe the primary key of the table login is not defined ( username )? I see username is nullable.

Another approach, a non-prepared statement might give an idea.

String sql = "insert into login(username, password) values('"
        + username + "', '" + password + "')";
System.out.println("sql = " + sql);
Statement pst = connection.createStatement();
pst.execute(sql);

If nothing helps, create a new table xxx and try all on that.

Actually, this error is caused when the number of values supplied and the number columns does not match. (ie) insert into table (col1,col2) values (val1) and insert into table (col1) values (val1,val2) both would generate same error.

I tried your code and it is perfectly working with Oracle. So, you can check for some spelling mistakes in names of the columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM