本文介紹了MySQL為什么我的自動(dòng)遞增在執(zhí)行插入時(shí)不是從1開(kāi)始?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
為什么當(dāng)我使用JDBC在數(shù)據(jù)庫(kù)中執(zhí)行插入操作時(shí),我的表AUTO_INCRENTIONS會(huì)被抬高。
填充完全空表的示例:
狗桌
DogId DogName
3 Woofer
4 Kujo
5 Spike
所有者表
OwnerId DogID OwnerName
6 3 George
7 4 John
8 5 Sam
預(yù)期結(jié)果
狗桌
DogId DogName
1 Woofer
2 Kujo
3 Spike
所有者表
OwnerId DogID OwnerName
1 1 George
2 2 John
3 3 Sam
實(shí)際代碼:
public void insertStuff(Something d)
{
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection(
"jdbc:mysql://" + this.getServer() + "/" + this.getDatabase(), user,
password);
con.setAutoCommit(false);
Statement s1 = (Statement) con.createStatement();
s1.executeUpdate("INSERT IGNORE INTO DOG (DOG_NAME) VALUES(""
+ d.getDogName() + "")");
Statement s2 = (Statement) con.createStatement();
s2.executeUpdate("INSERT IGNORE INTO OWNER (DOG_ID,OWNER_TITLE) VALUES ("
+ "(SELECT DOG_ID FROM DEVICE WHERE DOG_NAME =""
+ d.getDogName()
+ ""),"" + d.getOWNER() + "")");
Statement s3 = (Statement) con.createStatement();
s3.executeUpdate("INSERT IGNORE INTO KENNEL " + "("
+ "KENNEL_NAME,+ "OWNER_ID) " + "VALUES " + "( ""
+ d.getKennelName()
+ "","
+ """
+ ","
+ "(SELECT OWNER_ID FROM OWNER WHERE OWNER_TITLE=""
+ d.getOWNER() + "")" + ")");
}
con.commit();
}
catch (Exception e)
{
if (con != null)
try
{
con.rollback();
}
catch (SQLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
finally
{
if (con != null)
try
{
con.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
推薦答案
我只知道兩種情況:
(1)某些記錄已被刪除
(2)表上有一些修改此類(lèi)ID的觸發(fā)器
請(qǐng)注意,即使您對(duì)空表進(jìn)行了新的插入,如果以前有一些行,清空表時(shí)也不會(huì)重置自動(dòng)遞增ID計(jì)數(shù)器,并且它會(huì)從最后發(fā)出的編號(hào)開(kāi)始按順序繼續(xù),而不是從表中的實(shí)際記錄數(shù)繼續(xù)…
這篇關(guān)于MySQL為什么我的自動(dòng)遞增在執(zhí)行插入時(shí)不是從1開(kāi)始?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,