是否可以禁用MySQL中没有默认值的字段的自动空值插入?

发布于 2024-12-10 14:00:48 字数 1207 浏览 0 评论 0原文

是否有任何配置设置可以阻止 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一城柳絮吹成雪 2024-12-17 14:00:48

您可以启用“严格”模式 ,这会导致 MySQL 无法为无默认字段提供值的任何插入失败。

You can enable 'strict' mode, which'd cause MySQL to fail any inserts that don't provide values for default-less fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文