错误:java.sql.BatchUpdateException:字段'stu_id'没有默认值

时间:2013-07-18 19:18:14

标签: sql jdbc

我是JDBC和SQL的新手,我有这个程序但是当我运行它时,我收到以下错误:

java.sql.BatchUpdateException: Field 'stu_id' doesn't have a default value.

我试过操纵线

pst = con.prepareStatement("insert into student(first_name,last_name,address) values  (?,?,?)");

在值中添加第4个问号,并在插入到student()中添加stu_id。但是,他们只给出了其他错误。我不知道该怎么办?

package java11;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class PreparedExample {
public static void main(String[] args) {
    Connection con=null;
    PreparedStatement pst=null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/world","root","Sree7rama3**");
        pst = con.prepareStatement("insert into student(first_name,last_name,address) values (?,?,?)");

        for(int i=1;i<=20;i++){
            //pst.setInt(1, i);
            pst.setString(1, "Hello-"+i);
            pst.setString(2, "World-"+i);
            pst.setString(3,"HYD-"+i);
            pst.addBatch();
        }
        pst.executeBatch();

        System.out.println("Update is successful!");
    }catch (SQLException e) {
        System.out.println("There are some SQL errors!");
        e.printStackTrace();
    }catch (ClassNotFoundException e) {
        System.out.println("Driver class is not attached to this project!");
        e.printStackTrace();
    }finally{
        try {
            pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

看起来当你将stu_id添加到你的声明时,可能是你添加了这行

pst.setInt(1, i);

你有这些行

pst.setString(1, "Hello-"+i);
pst.setString(2, "World-"+i);
pst.setString(3,"HYD-"+i);

所以你要覆盖第一个参数(都是1)。

尝试

pst = con.prepareStatement("insert into student(stu_id,first_name,last_name,address) values (?,?,?,?)");



pst.setInt(1, i);
pst.setString(2, "Hello-"+i);
pst.setString(3, "World-"+i);
pst.setString(4,"HYD-"+i);