使用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()

 

你可能感兴趣的:(Python)