使用pymysql向mysql数据库插入一条数据报错 "pymysql.err.ProgrammingError: (1064..."

限于喜欢 提交于 2019-12-11 02:27:04

需求:

我的需求是要将字典值{'a': 1,'b': 2} 专为字符串插入数据库表指定字段,过去采取的办法是:

使用str()转换

info = {'a': 1,'b': 2}

sql = "INSERT INTO goods (title, type, info) VALUES ( '%s','%s','%s' )"
infoStr = str(info)
data = ('标题1', '2', infoStr)
cursor.execute(sql % data)
connect.commit()

以上操作报以下错误:

pymysql.err.ProgrammingError: (1064, "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 'a': 1, 'b': 2}','d' )' at line 1")

 

解决办法:

使用pymysql.escape_string()将字典值整体转换

info = {'a': 1,'b': 2}

sql = "INSERT INTO goods (title, type, info) VALUES ( '%s','%s','%s' )"
infoStr = pymysql.escape_string(info)
data = ('标题1', '2', infoStr)
cursor.execute(sql % data)
connect.commit()

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!