python - 使用带有字典值的 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 层次结构和配方表:
解决方案
我认为,根据您的解释,您有一组字典格式的食谱:
您用于在数据库中插入值的语法需要直接在变量上使用字典。无效语法的一个例子是:
{
'cuisine': None,
'id': 465645,
},{
'cuisine': None,
'id': 521693,
}
如果是这种情况,您需要迭代字典数组,并使用它的每个值(每个配方)启动 SQL 查询。您不能只执行一次查询来插入所有值。
例如,您可以使用 foreach 来迭代您的 recipes_data 上的所有值,将当前值存储在 recipe(例如)上。然后,在 foreach 中,您可以运行 cursor.execute()
推荐阅读
- python - gRPC HelloWorld - 从 Python 客户端向 ASP.NET Core 服务器发送消息时出错
- algorithm - 为什么我更喜欢二进制搜索而不是未排序数组中的线性搜索?
- typescript - Typescript:可以在构造函数中使用三元运算符或条件语句吗?
- android - 当应用程序在后台和手机锁定时的android webview地理定位跟踪
- python - 如何在 python 中使用 CRC/CRC 库?
- vba - 如果主 ODBC DSN 不存在,则使用备用 ODBC DSN
- linq - 如何将此 SQL 查询转换为 EF Core 中的 LINQ 查询?
- graphql-js - “只能创建 Nullable GraphQLType 的 NonNull 但得到:ID”
- excel - 如何处理 Excel 中的“数字存储为文本”?
- java - 使用 Streams 将嵌套的 for 循环从 Java 7 转换为 Java 8