更新 MySQL 中具有 JSON 格式的列?
要以 JSON 格式显示记录,请使用 MySQL concat()。我们首先创建一个表 −
mysql> create table DemoTable1373 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentDetails text -> ); Query OK, 0 rows affected (0.86 sec)
使用 insert 命令向表中插入一些记录。在这里,我们还没有插入任何内容 −
mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.18 sec)
使用 select 语句从表中显示所有记录 −
mysql> select * from DemoTable1373;
这将生成以下输出 −
+-----------+----------------+ | StudentId | StudentDetails | +-----------+----------------+ | 1 | NULL | | 2 | NULL | | 3 | NULL | +-----------+----------------+ 3 rows in set (0.00 sec)
以下是使用 JSON 格式更新 MySQL 字段的查询 −
mysql> update DemoTable1373 set StudentDetails=concat("{" "StudentName:", " John ,"," StudentAge:", 21,","," StudentCountryName: "," US","} "); Query OK, 3 rows affected (0.14 sec) Rows matched: 3 Changed: 3 Warnings: 0
让我们再次检查表记录 −
mysql> select * from DemoTable1373;
这将生成以下输出 −
+-----------+---------------------------------------------------------------+ | StudentId | StudentDetails | +-----------+---------------------------------------------------------------+ | 1 | {StudentName: John , StudentAge:21, StudentCountryName: US} | | 2 | {StudentName: John , StudentAge:21, StudentCountryName: US} | | 3 | {StudentName: John , StudentAge:21, StudentCountryName: US} | +-----------+---------------------------------------------------------------+ 3 rows in set (0.00 sec)
广告