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

需求:

我的需求是要将字典值{'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()
发布了14 篇原创文章 · 获赞 0 · 访问量 763

猜你喜欢

转载自blog.csdn.net/weixin_44725156/article/details/103479792