java實現向主鍵id自增的表中插入資料
阿新 • • 發佈:2019-02-04
問題
- 想要向mysql資料庫中插入一條記錄,因為設計的表時自動遞增的,那麼如果插入多條記錄,每次都要設定主鍵的話工作量會很大,而且難免會有重複的主鍵,這時候就要使用強大的主鍵自增的功能了。
在沒有使用主鍵自增時的程式碼是這樣子的
String insertSQL = "insert into user_t values(1, 'zzz', 'aaa', 20);";
statement = connection.prepareStatement(insertSQL);
statement.executeUpdate();
難免會報這樣的錯:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
在使用主鍵自增功能之後的程式碼:
String insertSQL = "insert into user_t(user_name, password, age) values(?, ?, ?)";
statement = connection.prepareStatement(insertSQL, PreparedStatement.RETURN_GENERATED_KEYS);
statement.setString(1, "zzz");
statement.setString(2, "aaa");
statement.setInt (3, 21);
statement.execute();
ResultSet rs = statement.getGeneratedKeys();
int id = 0;
if (rs.next()) {
id = rs.getInt(1);
}
但是又會報這樣的錯:
java.sql.SQLException: Field 'id' doesn't have a default value
完美解決方案:
- 在my.ini檔案中修改配置
#sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION" (註釋掉)
sql-mode ="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
- 檢視資料庫表是否設計為自動遞增