是否可以禁用MySQL中没有默认值的字段的自动空值插入?
是否有任何配置设置可以阻止 MySQL 为没有默认值且未在插入语句中指定的字段插入空值? 我更希望它拒绝无效的插入语句。
示例 - 我在 MySQL 中有下表:
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`val1` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`val2` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
如果运行此插入语句:
INSERT INTO test (val2) VALUES('a');
您会得到此响应:
Query OK, 1 row affected, 1 warning (0.00 sec)
来自 show warnings:
+---------+------+-------------------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------------------+
| Warning | 1364 | Field 'val1' doesn't have a default value |
+---------+------+-------------------------------------------+
1 row in set (0.00 sec)
来自 SELECT * FROM test
的响应:
+----+------+------+
| id | val1 | val2 |
+----+------+------+
| 1 | | asdf |
+----+------+------+
1 row in set (0.00 sec)
Is there any configuration setting to stop MySQL from inserting an empty value for fields which don't have a default value and weren't specified in the insert statement? I'd much prefer it rejected an invalid insert statement.
Example - I have the following table in MySQL:
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`val1` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`val2` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
If you run this insert statement:
INSERT INTO test (val2) VALUES('a');
You get this response:
Query OK, 1 row affected, 1 warning (0.00 sec)
Response from show warnings
:
+---------+------+-------------------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------------------+
| Warning | 1364 | Field 'val1' doesn't have a default value |
+---------+------+-------------------------------------------+
1 row in set (0.00 sec)
Response from SELECT * FROM test
:
+----+------+------+
| id | val1 | val2 |
+----+------+------+
| 1 | | asdf |
+----+------+------+
1 row in set (0.00 sec)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以启用“严格”模式 ,这会导致 MySQL 无法为无默认字段提供值的任何插入失败。
You can enable 'strict' mode, which'd cause MySQL to fail any inserts that don't provide values for default-less fields.