将复杂的json对象插入到SQL模式中

时间:2018-12-30 21:20:08

标签: python mysql sql

我有一个
形式的json对象

$stmt = $conn->prepare("SELECT * 
                        FROM `bigtree_pages` 
                        WHERE JSON_EXTRACT(`resources`, '$.XNCatDesc') LIKE ? and
                              JSON_EXTRACT(`resources`, '$.Brand') LIKE ? and 
                              JSON_EXTRACT(`resources`, '$.ItemDesc') LIKE ?");
$search_categorie = "%$categorie%";
$search_brand = "%$brand%";
$search_itemdesc = "%$itemdesc%";
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();

架构在哪里

{   
    "483329": 
    {"Dairy_free": false,
     "Gluten_free": true,
     "Vegetarian": false,
     "Vegan": false, 
     "ketagonic": false},

     "577539": 
     {"Dairy_free": true,
      "Gluten_free": false, 
      "Vegetarian": true, 
      "Vegan": true, 
      "ketagonic": false}
}


有没有一种方法可以不重新生成json,就可以使用mysqlcursors将json对象插入到mysql中?

    | id | Dairy_free | Gluten_free | Vegetarian | Vegan|  ketagonic|
    +----+------------+-------------+------------+------+-----------+

1 个答案:

答案 0 :(得分:1)

可以使用MySQLdb User's Guide之后的executemany

data = list(map(lambda x: tuple(x.values()), json_objects.values()))
# [(False, True, False, False, False), (True, False, True, True, False)]

c.executemany(
    """INSERT INTO allergies VALUES (Default, %s, %s, %s, %s, %s)""",
    data
)