我的需求是要将字典值{'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()