查看python shell中的代码:
>>> s = u'赵孟頫'.encode('gbk')
>>> s
'\xd5\xd4\xc3\xcf\xee\\'
'赵孟俯'的最后一个字节是\x5c,和反斜杠一样。它会导致一个sql错误。
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''?????\\')' at line 4
这是我的代码:
# db is mysql.connector object
sql = '''
INSERT INTO scraped_products(
site_prd_id,site_id,brand)
VALUES(
%(site_prd_id)s,%(site_id)s,%(brand)s)
'''
dat = {
'site_prd_id' : 'test',
'site_id' : 1,
'brand' : u'赵孟頫'.encode('gbk'),
}
self.db.ping(True, 3, 1)
self.db.cursor().execute(sql, dat)