首页 > 解决方案 > 使用带有字典值的 INSERT TO sql

问题描述

我正在使用 Python 3.6 mysql 8 和 mysql python connector 8
我正在尝试插入下表

| Recipes_id| title| Prep_time| servings | Summarize|  Very_healthy| Cuisine| img| source_url|
+-----------+------+----------+---------+----------+--------------+--------+----+-----------+

使用具有不同命名键的字典。

即字典的样本对象:

{
    'cuisine': None, 
    'id': 521693, 
    'img': None, 
    'prep_time': 5,
    'servings': 1, 
    'source_url': None,
    'summarize': 'Mango, Banana, Rasp...thie</a>.', 
    'title': 'Mango, Banana, Rasp... Smoothie',
    'very_healthy': None
}

此处,id键与recipe_id表中的列名不同。

MySQL查询如下:

Recipes_INSERT_SQL = (
    "INSERT INTO recipes "
    "(Recipes_id, title, Prep_time, servings, Summarize, Very_healthy, Cuisine, Img, Source_url) "
    "VALUES ( %(id)s, %(title)s, %(prep_time)s, %(servings)s, %(summarize)s, %(very_healthy)s, %(cuisine)s, %(img)s, %(source_url)s )"
)

cursor.execute(Recipes_INSERT_SQL, recipes_data)

请注意,字典键与列名不同
但错误是:

ProgrammingError(1064, "1064 (42000): 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 '%(id)s,
%(title)s, %(prep_time)s, %(serving)s, %(summarize)s, %(very_healthy)s, ' at line 1", 
'42000') 

如您所见,引擎甚至没有解析 (title)s 和其他名称。
我错过了什么吗?mysql 8 的占位符约定是文档中所述的 %(name)s。

这是 sql 层次结构和配方表:
在此处输入图像描述

标签: pythonmysql

解决方案


我认为,根据您的解释,您有一组字典格式的食谱:

您用于在数据库中插入值的语法需要直接在变量上使用字典。无效语法的一个例子是:

{
    'cuisine': None, 
    'id': 465645, 
},{
    'cuisine': None, 
    'id': 521693, 
}

如果是这种情况,您需要迭代字典数组,并使用它的每个值(每个配方)启动 SQL 查询。您不能只执行一次查询来插入所有值。

例如,您可以使用 foreach 来迭代您的 recipes_data 上的所有值,将当前值存储在 recipe(例如)上。然后,在 foreach 中,您可以运行 cursor.execute()


推荐阅读