com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
程式碼嘗試手動指定主鍵值:
if (c.getId() == -1) {
sql = "insert into category values(null,?,?,?,?,?)"; // 正確:null 讓自增生效
} else {
sql = "insert into category values(" + c.getId() + ",?,?,?,?,?)"; // 錯誤:手動給 ID 導致重複
}
CREATE TABLE category (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50), ...
);
String sql = "INSERT INTO category (name, descr, pid, isleaf, grade) VALUES (?, ?, ?, ?, ?)";
Statement.RETURN_GENERATED_KEYS:
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) { int generatedId = rs.getInt(1); }
INSERT INTO table (col1, col2)...),避免結構變更導致錯誤