我希望能够插入一行,并且如果看到主键已经存在,它将仅将该行更新为用户想要的内容。我能够编写UPSERT命令,但它给了我一个空指针错误。我不知道为什么。

这是我的代码:

  public PreparedStatement updateStudent(String studentId, String studentName, String sex, java.util.Date birthDate, double gpa) throws SQLException
    {
        // TODO: Use a PreparedStatement and return it at the end of the method
        java.sql.Date sd = new java.sql.Date(birthDate.getTime());

        String sql = "INSERT INTO student (sid, sname, sex, birthDate, gpa)
                      VALUES(?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE    \n" +
                      "sname=?, sex=?, birthDate=?, gpa=?";

        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, studentId);
        pstmt.setString(2, studentName);
        pstmt.setString(3, sex);
        pstmt.setDate(4, sd);
        pstmt.setDouble(5, gpa);
        pstmt.setString(6, studentName);
        pstmt.setString(7, sex);
        pstmt.setDate(8, sd);
        pstmt.setDouble(9, gpa);
        int row = pstmt.executeUpdate();
        return pstmt;
    }


这是我收到的错误:

Updating student 00567454:
Exception in thread "main" java.lang.NullPointerException
    at EnrollJDBC.updateStudent(EnrollJDBC.java:349)
    at EnrollJDBC.main(EnrollJDBC.java:85)

最佳答案

问题是birthDate为null,并且java.util.Date到java.sql.Date的转换不为null。所以我必须添加一个if else语句,如果birthDate为null

10-08 18:12