我正在尝试插入下表
| id | Dairy_free | Gluten_free | Vegetarian | Vegan| ketagonic|
+----+------------+-------------+------------+------+-----------+
来自python字典的行,其值无序(有些缺失)。
例如,字典中的元素之一可以是:
"Vegetarian": true,
"Vegan": true,
"ketagonic": false,
"recipe_id": 776990
因此,通过迭代字典,我创建了一个键值字符串元组以插入到特定的列中,例如mysql doc中的示例:
ALLERGIES_INSERT_SQL = ("INSERT INTO allergies (%s) VALUES (%s)")
for allergies_dict in allergies_list:
keys_as_string = ", ".join(list(allergies_dict.keys()))
values = list(allergies_dict.values())
values_as_strings = ", ".join([str(val) for val in values])
#now keys are in the form of 'Dairy_free, Gluten_free, Vegetarian, Vegan, recipe_id, ketagonic'
#and the values in the form of 'False, True, True, False, 521693, False'
cursor.execute(ALLERGIES_INSERT_SQL, (keys_as_string, values_as_strings))
但是我收到语法错误消息
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 '?) VALUES (?)' at line 1", '42000')