更新 JSON 格式的 MySQL 列?
mysqlmysqli database
要显示 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)