insert not working on mysql 5.7.12-0?

爷,独闯天下 提交于 2019-12-11 06:11:45

问题


my table structure is

  CREATE TABLE IF NOT EXISTS `emp` (
 `id` int(3) NOT NULL AUTO_INCREMENT,
 `name` varchar(11) DEFAULT NULL,
 `age` varchar(31) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

My query is :

 INSERT INTO `emp` (`id`, `name`) VALUES ('1', 'prashant');

This is working with all the MYSQL versions below 5.7, but not working with MYSQL version 5.7.12-0ubuntu1

Getting error :

#1364 - Field 'age' doesn't have a default value

What is new in this version ??

Try it on mysql version below 5.7 ,you will see the difference.

Thanks :-)


回答1:


It would be a huge surprise if this worked in any version of mysql at all. Copy paste this into sqlfiddle.com (mysql 5.6 or 5.5) and confirm for yourself.

age is defined as varchar(31) and not null. Thus your insert statement should have a value for that column. Or you should give it a default value. While you are at it, change it to a more appropriate data type.

 CREATE TABLE IF NOT EXISTS `emp` (
 `id` int(3) NOT NULL AUTO_INCREMENT,
 `name` varchar(11) DEFAULT NULL,
 `age` int(3) NOT NULL default 0,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Updated:

Thinking about this some more I think you have switched off Strict Mode in your older version of mysql

Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. A value can be invalid for several reasons. For example, it might have the wrong data type for the column, or it might be out of range. A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. (For a NULL column, NULL is inserted if the value is missing.) Strict mode also affects DDL statements such as CREATE TABLE.

So my original statement is wrong! With string mode off, the default for varchar is probably '' (not sure though never used strict mode off)




回答2:


In your table age described as not null.

`age` varchar(31) NOT NULL

So, it is required field for insert.




回答3:


The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.You have to give value for age also in your insert query because it cannot be null.For eg:-

insert into emp(`id`,`name`,`age`) values('1','rahul','26')

hope this helps!!.Comment for further query



来源:https://stackoverflow.com/questions/38374536/insert-not-working-on-mysql-5-7-12-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!