将INSERT TO sql与字典值一起使用

时间:2019-01-01 13:26:27

标签: python mysql

我正在使用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') 

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

这是sql层次结构和配方表:
enter image description here

1 个答案:

答案 0 :(得分:0)

我认为,根据您的解释,您可以使用字典格式的一组食谱:

用于在数据库中插入值的语法需要在变量上直接具有字典。无效语法的示例如下:

npm install -g @angular/cli@latest

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

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