[英][Java]Error when Inserting SQL, auto increment in the table - userId
[英]SQL userID auto increment
Mysql數據庫就是這樣;
userID -> primaryKey, required, unsigned integer, auto increment, unique
usermail -> unique,varchar,required
我正在創建新用戶。 userId是自動遞增。 如果之前插入了用戶郵件,則會發生錯誤。 我的問題是
Let's think that userID is between 1-9.(there are 9 users now).
Somebody has inserted same usermail before and took error.
After that,new user inserted another usermail but userID became 11 instead 10.
Why? What should i do to make it 10?
引起錯誤時,它似乎正在插入新行並遞增唯一標識。 出錯時,您將需要在表中查詢最新的ID並重置自動增量值
ALTER TABLE `table_name` AUTO_INCREMENT =new_number_here
在這里找到: http : //forums.mysql.com/read.php?20,16088,17748#msg-17748
您必須將insert子句與select選擇合並,如下所示。
這是mysql的一種行為,它也會為錯誤和成功插入而增加計數器
INSERT INTO [table name] SELECT '[value1]', '[value2]' FROM DUAL
WHERE NOT EXISTS(
SELECT [column1] FROM [same table name]
WHERE [column1]='[value1]'
AND [column2]='[value2]' LIMIT 1 )
在這里,您可以看到如何使用此技術防止insert
子句insert-where-not-exists存在,插入數據時計數器將增加,而重復數據將被忽略
您是否需要從數據庫屬性本身增加userID。 因為我的意思是,在插入任何記錄之前,只需從數據庫中檢索最后一個用戶ID,將其存儲在整數變量中,然后對其進行遞增,然后將其與新記錄一起插入數據庫即可。
假設您的最后一個用戶ID為9。使用此查詢- Select max(userID) from "your table";
int x=0;
SqlDataReader dr=com.ExecuteReader();
if(dr.HasRows)
{
While(dr.Read())
{
x=Convert.ToInt32(dr.GetString(0).ToString);
}
}
x=x+1;
現在,由於您有了新的x
值,因此可以輕松地將其插入新記錄的數據庫中。 這樣就可以遵循自動遞增的方式,即使發生故障也不會進行插入,並且UserID
不會增加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.