1

Python シェルのコードを見てください。

>>> 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)
4

1 に答える 1

2

それを機能させるには、追加の作業が必要なソリューションがあります。次のコード例は、データをMySQL 16 進数リテラルに変換し、エスケープ、引用、または変換せずに MySQL に送信します。クエリを実行する方法は少し異なりますが、今のところ役立つことを願っています。

import mysql.connector

cnx = mysql.connector.connect(database='test', user='root',
                              charset='gbk', use_unicode=False)
cur = cnx.cursor()

cur.execute("DROP TABLE IF EXISTS gbktest")
table = (
    "CREATE TABLE gbktest ("
    "id INT AUTO_INCREMENT KEY, "
    "c1 VARCHAR(40)"
    ") CHARACTER SET 'gbk'"
)
cur.execute(table)

def gbk_to_hexstr(value):
    """Convert value to Hexadecimal Literal for MySQL
    """
    return "0x{0}".format(''.join(
        ["{0:x}".format(ord(c)) for c in value.encode('gbk')]))

# Convert your Unicode data using gbk_to_hexstr
data = {
    'c1' : gbk_to_hexstr(u'赵孟頫'),
}

# Use MySQLCursor.execute() _not_ passing data as second argument
cur.execute("INSERT INTO gbktest (c1) VALUES ({c1})".format(**data))
cur.execute("SELECT c1 FROM gbktest")

# Print the inserted data as Unicode
for row in cur:
    print(row[0].decode('gbk').encode('utf8'))
于 2013-07-15T12:04:13.453 に答える