当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL自增列插入0值的解决方案

MySQL自增列插入0值的解决方案

2017年12月12日  | 移动技术网IT编程  | 我要评论

红安县教育局,天堂狂想曲,江苏图书批发市场

在将数据库从mssql迁移到mysql的过程中,基于业务逻辑的要求,需要在mysql的自增列插入0值。在mssql中是这样完成的:
复制代码 代码如下:

string sql;sql = " set identity_insert dbo.appusers on "
+ " insert dbo.appusers (id, islocked, ismustchangelocalpassword, isavailable, name, sequence, createdby, createdtime, updatedby, updatedtime) "
+ " values (0, 1, 0, 0, '[system]', 0, 0, getdate(), 0, getdate()) "
+ " set identity_insert dbo.appusers off "
+ " dbcc checkident ('dbo.appusers', reseed, 0) ";
db.database.executesqlcommand(sql);

mysql官方文档中是这样写的
复制代码 代码如下:

no_auto_value_on_zero affects handling of auto_increment columns. normally, you generate the next sequence number for the column by inserting either null or 0 into it. no_auto_value_on_zero suppresses this behavior for 0 so that only null generates the next sequence number.
this mode can be useful if 0 has been stored in a table's auto_increment column. (storing 0 is not a recommended practice, by the way.) for example, if you dump the table with mysqldump and then reload it, mysql normally generates new sequence numbers when
it encounters the 0 values, resulting in a table with contents different from the one that was dumped. enabling no_auto_value_on_zero before reloading the dump file solves this problem. mysqldump now automatically includes in its output a statement that enables no_auto_value_on_zero, to avoid this problem.

大致的意思是说:no_auto_value_on_zero会影响自增列,一般情况下,获得下一个序列值的方法是对自增列插入0或者null值。no_auto_value_on_zero会改变这个缺省的行为,使得只有插入null值才能获取下一个序列值。这种方式对于要将0值插入自增列是有用的。(顺便指出,0值是不推荐使用在自增列的)例如,如果你使用mysqldump备份数据表然后再恢复它,mysql一般情形下会0值自动产生新的序列值,结果是造成从备份恢复数据错误。在恢复数据前,启用no_auto_value_on_zero可以解决这个问题。mysqldump现在会自动在输出的语句中包含no_auto_value_on_zero来解决这个问题。
在mysql中需要这样
复制代码 代码如下:

sql = " set session sql_mode='no_auto_value_on_zero'; insert appusers (id, islocked, ismustchangelocalpassword, isavailable, name, sequence, createdby, createdtime, updatedby, updatedtime) "
+ " values (0, 1, 0, 0, '[system]', 0, 0, current_timestamp, 0, current_timestamp) ";

至此问题解决。
后记
由于业务逻辑需要,在自增列会存在0值,为了在windows平台和linux平台的mysql之间复制数据,增加全局变量设置,在my.ini和my.cnf中分别添加no_auto_value_on_zero设置到sql-mode行,例如:
复制代码 代码如下:

//my.ini 该文件在windows7或windows2008操作系统中位于 c:\programdata\mysql\mysql server 5.6 目录下(采用msi安装方式)# set the sql mode to strict
sql-mode="strict_trans_tables,no_auto_create_user,no_engine_substitution,no_auto_value_on_zero"

重启mysql服务后,查看sql-mode全局变量的办法
select @@global.sql_mode;
>>>>> 版权没有 >>>>> 欢迎转载 >>>>> 原文地址 >>>>> http://www.cnblogs.com/jlzhou >>>>> 雄鹰在鸡窝里长大,就会失去飞翔的本领,野狼在羊群里成长,也会爱上羊而丧失狼性。人生的奥妙就在于与人相处。生活的美好则在于送人玫瑰。和聪明的人在一起,你才会更加睿智。和优秀的人在一起,你才会出类拔萃。所以,你是谁并不重要,重要的是,你和谁在一起。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网