MySQL抛出“java.sql.SQLException:列数与第1行的值计数不匹配”

时间:2017-11-05 12:53:37

标签: java mysql jdbc

String QueryText= "INSERT INTO user_details (fname,lname,user_email,birth_day,birth_mnth,birth_year,addr,pwd) VALUES ('"+fname+"','"+lname+"','"+user_email+"','"+birth_day+"','"+birth_mnth+"','"+birth_year+"','"+gender+"','"+addr+"','"+pwd+"')";

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdatabase", "root","");

Statement st=con.createStatement();

int rt = st.executeUpdate(QueryText);

2 个答案:

答案 0 :(得分:1)

为避免出现性别和SQL注入问题,最好使用PreparedStatement代替:

String queryText = "INSERT INTO user_details "
      + "(fname, lname, user_email, birth_day, birth_mnth, birth_year, gender, addr, pwd) "
      //----------------------------------------------------------------^
      + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

Connection con = DriverManager.getConnection(
                      "jdbc:mysql://localhost:3306/jspdatabase", "root", "");

try(PreparedStatement pst = con.prepareStatement(queryText);){
    pst.setString(1, fname);
    pst.setString(2, lname);
    pst.setString(3, user_email);
    pst.setString(4, birth_day);   //If one of the three is integer type
    pst.setString(5, birth_mnth);  //You have to use setInt(...) instead
    pst.setString(6, birth_year);  //of setString(...)
    pst.setString(7, gender);
    pst.setString(8, addr);
    pst.setString(9, pwd);
    int rt = pst.executeUpdate();
    ...
}

真正的问题是你使用8个参数并尝试插入9个值,这就是你得到这个错误的原因。

答案 1 :(得分:0)

很明显,列数与您提供的值不匹配。

您声明了8列并提供了9个值。

您的专栏未声明性别