29

I'm trying to create a JSON object and then read the values from it into MySQL table. But I'm facing errors and I'm new to both JSON and MySQL.

SET @j = '{"key1": "value1", "key2": "value2"}';
CREATE TABLE Person (name int,id int);
INSERT INTO Person (name,id) SELECT * FROM OPENJSON(@j) WITH (name int,id int);
Madan Sapkota
  • 25,047
  • 11
  • 113
  • 117
rj_23495
  • 293
  • 1
  • 3
  • 6

1 Answers1

58

On creating table set your field as JSON datatype.

CREATE TABLE `person` (
  `name` json DEFAULT NULL
);

And Insert JSON data into it,

INSERT INTO `person` (`name`)
VALUES ('["name1", "name2", "name3"]');

Or Insert JSON data by Key:Value

INSERT INTO person VALUES ('{"pid": 101, "name": "name1"}');
INSERT INTO person VALUES ('{"pid": 102, "name": "name2"}');

Select JSON data,

SELECT * FROM `person` WHERE JSON_CONTAINS(name, '["name1"]');

Note: Only supported by MySQL 5.7 (or higher) using InnoDB.

Ben in CA
  • 688
  • 8
  • 22
saravanabawa
  • 1,607
  • 1
  • 16
  • 23
  • 2
    "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json DEFAULT NULL, )' at line 2" this is the error i am encountering – rj_23495 Dec 02 '16 at 12:01
  • 2
    MySQL 5.7 InnoDB or higher versions only supports. – saravanabawa Dec 02 '16 at 12:16