我的目标是使用mysql.connector库将JSON对象存储到JSON类型的MySQL数据库字段中。在import mysql.connector
import json
jsonData = json.dumps(origin_of_jsonData)
cnx = mysql.connector.connect(**config_defined_elsewhere)
cursor = cnx.cursor()
cursor.execute('CREATE DATABASE dataBase')
cnx.database = 'dataBase'
cursor = cnx.cursor()
cursor.execute('CREATE TABLE table (id_field INT NOT NULL, json_data_field JSON NOT NULL, PRIMARY KEY (id_field))')
现在,下面的代码工作正常,我的问题的焦点是“%s”的使用:
^{pr2}$
我的问题是:当将变量aValue组合成一个字符串时,我非常严格地遵守'...{}'.format(aValue)(或f'...{aValue}')的使用,从而避免使用{}(无论我的原因是什么,我们不在这里讨论它们-但这是我希望尽可能保留它的方式,因此我的问题是)。在
在任何情况下,我都无法创建将jsonData存储到mySql数据库中的东西,使用类似于上述结构的东西,并使用'...{}'.format()(任何形状或形式)而不是{}。例如,我(在许多迭代中)尝试过insert_statement = "INSERT INTO table (id_field, json_data_field) VALUES ({}, {})".format(1, jsonData)
cursor.execute(insert_statement)
但无论我如何转动和扭转它,我总是得到以下错误:ProgrammingError: 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 '[some_content_from_jsonData})]' at line 1
现在我的问题是:
1)是否有方法避免在此处使用我缺少的%s?在
2)如果没有,为什么?是什么让这不可能?是cursor.execute()函数,还是它是一个JSON对象,还是完全不同?难道{}.format()不应该做%s所能做的一切,甚至更多?在