Python使用pymysql向XAMPP存blob报1064SQL语法错误如何解决
报错原因
你遇到的1064语法报错本质是直接通过Python字符串格式化拼接二进制Blob数据到SQL语句中导致的:二进制图片流包含大量特殊字符(单引号、转义序列等),插入到SQL模板中会破坏原有语法结构,同时这种写法还存在SQL注入风险。
解决方法
- 放弃
%字符串拼接SQL的写法,改用pymysql提供的参数化查询能力,参数化查询会自动处理不同数据类型的转义逻辑,完美适配二进制Blob类型的插入 - 移除SQL模板中占位符
%s外层的单引号,pymysql参数化不需要手动为值加引号 - 参数以元组形式作为
cursor.execute的第二个参数传入,不要直接拼到SQL字符串里 - 补充文件资源关闭逻辑,避免文件句柄泄漏
修改后的完整代码
def save_to_db(): get_id_no = id_no_var.get() get_first_name = first_name_var.get() get_middle_name = middle_name_var.get() get_last_name = last_name_var.get() get_course = course_var.get() raw_qr_code_id = str(get_id_no + get_first_name + get_middle_name + get_last_name + get_course) final_qr_code_id = str(raw_qr_code_id.replace(" ", "")) filename = final_qr_code_id + ".png" # 改用with上下文自动关闭文件 with open(filename, 'rb') as image: image_binary = image.read() # 参数化查询写法:占位符不要加单引号,参数单独作为第二个参数传入 cursor.execute("""INSERT INTO `student_information` (`id_no`, `first_name`, `middle_name`, `last_name`, `course`, `qr_code_id`, `qr_code_blob`) VALUES (%s, %s, %s, %s, %s, %s, %s)""", (get_id_no, get_first_name, get_middle_name, get_last_name, get_course, final_qr_code_id, image_binary)) connect_db.commit()
内容的提问来源于stack exchange,提问作者k1dlat
相关产品推荐
相关产品推荐

