Update a MySQL column with JSON format?



To display records like JSON format, use MySQL concat(). Let us first create a table −

mysql> create table DemoTable1373    -> (    -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,    -> StudentDetails text    -> ); Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command. Here, we haven’t inserted anything −

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)

Display all records from the table using select statement −

mysql> select * from DemoTable1373;

This will produce the following output −

+-----------+----------------+ | StudentId | StudentDetails | +-----------+----------------+ |         1 | NULL         | |         2 | NULL         | |         3 | NULL         | +-----------+----------------+ 3 rows in set (0.00 sec)

Following is the query to update a MySQL field with JSON format −

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

Let us check the table records once again −

mysql> select * from DemoTable1373;

This will produce the following output −

+-----------+---------------------------------------------------------------+ | 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)
Updated on: 2019-11-11T09:25:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements