MySQL为什么我的自动递增在执行插入时不是从1开始?
为什么当我使用JDBC在数据库中执行插入操作时,我的表AUTO_INCRENTIONS会被抬高。
填充完全空表的示例:
狗桌
DogId DogName
3 Woofer
4 Kujo
5 Spike
所有者表
OwnerId DogID OwnerName
6 3 George
7 4 John
8 5 Sam
预期结果
狗桌
DogId DogName
1 Woofer
2 Kujo
3 Spike
所有者表
OwnerId DogID OwnerName
1 1 George
2 2 John
3 3 Sam
实际代码:
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)表上有一些修改此类ID的触发器
请注意,即使您对空表进行了新的插入,如果以前有一些行,清空表时也不会重置自动递增ID计数器,并且它会从最后发出的编号开始按顺序继续,而不是从表中的实际记录数继续...
相关文章