Art*_*tur 8 mysql sql auto-increment
今天我遇到了一个我见过的MySQL最奇怪的东西.我有一个简单的表:
CREATE TABLE `features`
(
`feature_id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
`feature_name` varchar(100) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
PRIMARY KEY (`feature_id`),
UNIQUE KEY `feature_name_key` (`feature_name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
Run Code Online (Sandbox Code Playgroud)
我在Java和mysql-connector-java-5.1.15库中插入数据.feature_name中的数据可能重复,我只想要唯一的值.我可以使用INSERT IGNORE但是如果数据太长我可能会忽略它所以我使用它:
pstmt = conn.prepareStatement(
"INSERT INTO features (feature_name) VALUES (?)" );
for ( String featureName: data4db.keySet() )
{
pstmt.setString(1, featureName );
try
{
pstmt.executeUpdate();
}
catch ( SQLException se )
{
if ( se.getErrorCode() == 1062 ) // duplicate entry
{
continue; // ignore
}
throw se; // do not ignore anything else
}
}
Run Code Online (Sandbox Code Playgroud)
数据插入数据库之后,我注意到有些问题我甚至没想到.上表中大约有4000条记录可以.唯一的问题是由于重复的主键导致无法插入某些数据,因此我查看了此表的auto inc值的外观.事实证明,对于大多数数据,下一个相邻行的id按预期递增1.因为我不知道有时feature_id增加了3,5,1000,100000 - 完全随机的值.因此,我在这个表中"不合适",因为一旦id达到medium int的max val就无法插入.
怎么会发生这种情况?有没有人遇到类似的?值得一提的是,只有一个程序有一个线程写入此表.我还有一个表几乎相同 - 列宽和名称不同.对于这个,存在类似的问题.
BTW - 更多数据:
mysql> show global variables like 'auto_inc%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| auto_increment_increment | 1 |
| auto_increment_offset | 1 |
+--------------------------+-------+
2 rows in set (0.01 sec)
mysql> show global variables like 'ver%';
+-------------------------+------------------------------+
| Variable_name | Value |
+-------------------------+------------------------------+
| version | 5.5.10 |
| version_comment | MySQL Community Server (GPL) |
| version_compile_machine | x86 |
| version_compile_os | Win32 |
+-------------------------+------------------------------+
Run Code Online (Sandbox Code Playgroud)
感谢您提前提示.
Mic*_*.V. 13
这是正常的MySQL行为.发生的事情如下:您将数据插入auto_increment键3,然后您获得了重复键,因为您的feature_name_key被定义为唯一.事实上,MySQL将"浪费"整数4并将继续下一个,它将不会重用由于键约束而导致写入失败的整数.
如果你有这样的事情:
PK | feature_name_key
1 | key1
2 | key2
3 | key3
4 | key1 (fails due to constraint, 4 is not going to be used for next successful insertion, hence the gaps in your primary key)
Run Code Online (Sandbox Code Playgroud)
然后你输掉了可用于主键/ auto_increment的整数.在插入或构建表格时重新考虑您的策略以保存您的数据.