You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MariaDB插入JSON类型数据报CONSTRAINT约束错误的求助

MariaDB JSON字段插入报错(ERROR 4025)排查与解决

问题详情

创建数据库及表操作:

MariaDB [(none)]> use db1
Database changed

MariaDB [db1]> create table user(id int not null, profile json);
Query OK, 0 rows affected (0.028 sec)

执行插入语句时持续报错:

MariaDB [db1]> insert into user(`id`, `profile`) values(1, '{name: "irvan"}');
ERROR 4025 (23000): CONSTRAINT `user.profile` failed for `db1`.`user`

MariaDB [db1]> INSERT INTO user(`id`, `profile`) VALUES(1, '{name: "irv" }');
ERROR 4025 (23000): CONSTRAINT `user.profile` failed for `db1`.`user`

MariaDB [db1]> INSERT INTO user(`id`, `profile`) VALUES(1, '');
ERROR 4025 (23000): CONSTRAINT `user.profile` failed for `db1`.`user`

数据库版本:

C:\xampp\mysql\bin>mysql -V
mysql  Ver 15.1 Distrib 10.4.27-MariaDB, for Win64 (AMD64), source revision 
0946c99e7d6f7ac9dfcf3e60dae6ae85161d5ef2

错误原因

  1. JSON格式不合法:标准JSON要求键名必须用双引号包裹,你提供的{name: "irvan"}中name未加双引号,属于无效JSON
  2. 空字符串不是合法JSON:''不符合JSON语法规范,无法被JSON字段接受

解决方案

使用标准JSON格式执行插入:

-- 键名用双引号的合法JSON
INSERT INTO user(`id`, `profile`) VALUES(1, '{"name": "irvan"}');

-- 插入空JSON对象
INSERT INTO user(`id`, `profile`) VALUES(2, '{}');

-- 插入NULL(字段未设置NOT NULL,允许为空)
INSERT INTO user(`id`, `profile`) VALUES(3, NULL);

验证工具

可通过JSON_VALID()函数快速校验字符串是否为合法JSON:

SELECT JSON_VALID('{name: "irvan"}'); -- 返回0,非法
SELECT JSON_VALID('{"name": "irvan"}'); -- 返回1,合法

内容的提问来源于stack exchange,提问作者Irvan Hilmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:57:10