2017-06-22 57 views
0

我需要使用Python3腳本將幾個非ASCII字符(如è或甚至其他字母)插入到MySQL 5.7數據庫字符串中。我將utf8mb4中感興趣的表的所有列轉換。使用Python和MySQL進行字符串編碼

db1 = MySQLdb.connect (
host="host1", 
user="user1", 
passwd="secret", 
db="db1" 
) 

cursor1 = db1.cursor() 
cursor1.execute("USE db1") 

連接我可以正確地存儲串與è。與串生成代替以下錯誤:

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2026' in position 1022: ordinal not in range(256) 

反之亦然,與

db1 = MySQLdb.connect (
host="host1", 
user="user1", 
passwd="secret", 
db="db1" 
) 

cursor1 = db1.cursor() 
cursor1.execute("USE db1") 
cur.execute("SET NAMES utf8mb4;") 
cur.execute("SET CHARACTER SET utf8mb4;") 
cur.execute("SET character_set_connection=utf8mb4;") 

連接產生由於è一個錯誤:

_mysql_exceptions.OperationalError: (1366, "Incorrect string value: '\\xE8 string...' for column 'column1' at row 1") 

è具有十六進制代碼E8

怎麼了?

回答

1

你應該嘗試的編碼設置爲UTF-8在連接到數據庫做這樣的事情:

db1 = MySQLdb.connect (
host="host1", 
user="user1", 
passwd="secret", 
db="db1" 
use_unicode=True, 
charset="utf8" 
) 
相關問題