我的数据库添加功能有问题。以下代码在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;
}
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
您的SQL格式错误,您正尝试使用UPDATE的语法进行INSERT。
这是标准INSERT的外观
INSERT INTO users (idCardNr,nationality,name,address,photo,status,gender,nationalNr,birthDate,birthPlace,created,country) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
在将SQL放入代码之前手动测试SQL总是一个好主意。
答案 1 :(得分:0)