我的数据库添加函数有问题。下面的代码挂在ExecuteUpdate语句上,它不会抛出异常,因此我无法找出问题所在。

public static boolean addUser(User userToAdd) throws Exception {
    boolean isAdded = false;

    if (checkConnection()) {
        try {
            if (isUnique(userToAdd.getIdCardNumber())) {
                PreparedStatement pstmt = connection.prepareStatement("INSERT INTO users SET "
                        + "idCardNr = ?,nationality = ?,name = ?,"
                        + "address = ?,photo = ?,status = ?,gender = ?,"
                        + "nationalNr = ?,birthDate = ?,birthPlace = ?,"
                        + "created = ?, country = ?");

                pstmt.setString(1, userToAdd.getIdCardNumber());
                pstmt.setString(2, userToAdd.getNationality());
                pstmt.setString(3, userToAdd.getFullName());
                pstmt.setString(4, userToAdd.getAddress());
                pstmt.setString(5, userToAdd.getPhotoPath());
                pstmt.setString(6, userToAdd.getStatus());
                pstmt.setString(7, userToAdd.getGender());
                pstmt.setString(8, userToAdd.getRegisterNumber());
                pstmt.setString(9, userToAdd.getBirthday());
                pstmt.setString(10, userToAdd.getBirthPlace());
                java.sql.Timestamp current = new java.sql.Timestamp(System.currentTimeMillis());
                userToAdd.setCreated(current);
                pstmt.setTimestamp(11, userToAdd.getCreated());
                pstmt.setString(12, userToAdd.getCountry());


                int rowsAffected;
                try {
                   rowsAffected = pstmt.executeUpdate();
                } catch (SQLException e) {
                    throw new Exception("Exception while executing update: " + e.getMessage());
                }


                if (rowsAffected != 0) {
                    isAdded = true;
                    pstmt.close();
                }

            } else {
                System.out.println("User already in database");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return isAdded;
}

有人能帮我调试一下吗?

最佳答案

您的SQL格式不正确,您正在尝试使用更新语法插入。
这就是标准插入的外观

INSERT INTO users (idCardNr,nationality,name,address,photo,status,gender,nationalNr,birthDate,birthPlace,created,country) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)

在将SQL放入代码之前手动测试它总是一个好主意。

关于java - PreparedStatement卡在executeUpdate函数上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11187413/

10-11 01:21