插入 JSON 对象时 Python pymysql 语法错误

标签 python mysql json pymysql

在 Python 中插入 SQL 数据库的表时出现以下错误:

pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL 
syntax; check the manual that corresponds to your MariaDB server 
version for the right syntax to use near \'"Black": {"b": "125.98", 
"a": "126.796", "L": "117.245"}, "Pink": {"b": "130.286\' at line 1')

SQL命令是:

json1 = json.dumps(meanLAB_vals_dict) # convert python dict to json string 
json2 = json.dumps(deltaE_dict)
sql_command = """INSERT INTO data_integrity_tool VALUES (%d, %d, %s, %s)""" %(i, image_id, json1, json2)

cursor.execute(sql_command)
connection.commit()

meanLAB_vals_dict是:

{'Black': {'b': '125.98', 'a': '126.796', 'L': '117.245'}, 'Pink': 
{'b': '130.286', 'a': '180.918', 'L': '169.0'}, 'Green': {'b': 
'135.531', 'a': '103.51', 'L': '144.755'}, 'Violet': {'b': '109.878',
'a': '136.653', 'L': '122.02'}, 'Grey': {'b': '123.327', 'a': 
'125.612', 'L': '139.429'}, 'Yellow': {'b': '195.571', 'a': 
'112.612', 'L': '234.694'}, 'Red': {'b': '153.449', 'a': '177.918',
'L': '163.939'}, 'White': {'b': '128.02', 'a': '128.939', 'L': 
'243.878'}, 'Blue': {'b': '84.7551', 'a': '122.98', 'L': '163.673'}}

deltaE_dict是:

{'Black': '38.5187', 'Pink': '38.6975', 'mean delta E': '28.0643', 
'Green': '42.6365', 'Violet': '35.5018', 'Grey': '19.8903', 'Yellow':
'24.5115', 'Red': '40.0078', 'White': '4.4993', 'Blue': '8.31544'}

iimage_id是两个整数(迭代的索引)。 以下是data_integrity_tool表:

sql_command = """CREATE TABLE IF NOT EXISTS data_integrity_tool (
                 id_              INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,  
                 image_id         INTEGER NOT NULL,
                 mean_lab_values  TEXT,
                 delta_e_values   TEXT);"""

我知道已经存在一些类似的问题,但是,它们是针对 PHP 的,我对此一无所知,而且,我对 SQL 完全陌生。

最佳答案

您似乎没有指定在sql查询中插入数据的字段名称。如果要插入 json 数据,也可以使用 blob 作为数据类型。这更安全。也不要在插入查询中强制转换 no。

如果您考虑我的回答,那么您的 sql 语句应该是这样的。 建表命令:

sql_command = """如果不存在则创建表 data_integrity_tool ( id_ INTEGER NOT NULL 主键自动递增, image_id 整数非空, 平均值实验室值BLOB, delta_e_values BLOB);"""

插入命令:

sql_command = """插入 data_integrity_tool(id_,image_id,mean_lab_values,delta_e_values) 值 (%d, %d, %s, %s)"""%(i, image_id, json1, json2)

关于插入 JSON 对象时 Python pymysql 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43202222/

相关文章:

python - 服务器从 Flask 向多个客户端发送事件

python - 如何在没有pip的情况下安装python模块?

mysql - R 编程 - 将日语字符插入 MySQL

android - 在android中动态生成JSONObject

java - 声纳 "Make transient or serializable"错误

python - 如何在 python 脚本中调用此方法?

php - 论坛 - 按上次事件在多个页面上排序的主题

php - 用我自己的数字和字母自动递增

php - 如何阻止 CakePHP 在输出中放置注释标签

python - Python 中的华氏度转换器,使用 try/except 命令排除字母