How to store data in MySQL as JSON?

MySQLMySQLi JSON

We can store data in MySQL as JSON with the help of JSON data type. The following is an example.

Let us now create a table.

mysql>  CREATE table JsonAsMySQLDemo
   -> (
   ->  id int,
   ->  name varchar(100),
   -> PageDemo JSON,
   -> eventInfo JSON
   -> );
Query OK, 0 rows affected (0.67 sec)

Storing records into JSON data type.

mysql> INSERT into JsonAsMySQLDemo values
   -> (
   ->  1,
   -> 'John',
   -> '{"Page1":"/"}',
   -> '{"OperatingSystem":"Windows"}'
   -> );
Query OK, 1 row affected (0.24 sec)

mysql> insert into JsonAsMySQLDemo values
   ->    (
   ->    2,
   ->    'Bob',
   ->     '{"Page2":"/"}',
   ->     '{"OperatingSystem":"Solaris"}'
   ->    );
Query OK, 1 row affected (0.14 sec)

To display all records, use the SELECT

mysql> select *from JsonAsMySQLDemo;

The following is the output.

+------+------+----------------+--------------------------------+
| id   | name | PageDemo       | eventInfo                      |
+------+------+----------------+--------------------------------+
|    1 | John | {"Page1": "/"} | {"OperatingSystem": "Windows"} |
|    2 | Bob  | {"Page2": "/"} | {"OperatingSystem": "Solaris"} |
+------+------+----------------+--------------------------------+
2 rows in set (0.00 sec)
raja
Published on 23-Nov-2018 10:53:03
Advertisements