1

我是 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 个问号,并将 stu_id 插入到 student() 中。但是,他们只给出了其他错误。我不知道该怎么办?

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

1 回答 1

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);
于 2013-07-18T19:20:34.067 回答