python - 使用带有字典值的 INSERT TO sql

标签 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

最佳答案

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

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

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

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

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

关于python - 使用带有字典值的 INSERT TO sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53995812/

相关文章:

mysql - 按一列与另一列的值完全相同的位置排序

Python Twitter search.tweets with until

python - 按字符串中单词的数量对字符串列表进行排序

python - 模糊逻辑: How to detect when a 404 is not actually an error page?

mysql - 如何删除和重新填充 mysql 数据库?

php - 带图片的博客文章?

python - 根据多个条件设置numpy数组的值

python - Pandas 系列在值之间过滤

mysql - 是否有可能获得 InnoDB 内部行 ID?

mysql - 如何在 SQL 中查找值的百分比?