所以我的主要問題是,我錯過了我的db連接字符串中的charset="utf8"
。在我有了之後,其他一切都很簡單。
下面是我的一些測試代碼,作爲參考,以防其他人遇到相同的問題。它將特殊值插入到一個數據庫中,然後從該數據庫讀取它們並將其插入到不同的數據庫中。我使用了第三方工具來查詢數據庫並驗證結果。我做的最後一個測試是基於名稱的刪除:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
db1 = MySQLdb.connect(host="10.100.10.2",
user="root",
passwd="",
db="db1",
charset="utf8"
)
db1.autocommit(True)
cur1 = db1.cursor()
db2 = MySQLdb.connect(host="10.100.10.2",
user="root",
passwd="",
db="db2",
charset="utf8"
)
db2.autocommit(True)
cur2 = db2.cursor()
valueSpecialCharacters = u"`[email protected]#$%^&*()_+[]\\;',./{}|:\"<>?"
valueSpecialCharacters2 = u"¢¥¦§©«¬®æƸɅɆɜʘɷɸӒӔӥӺӾسشصضطّ٦۞"
valueSpecialCharacters3 = u"۩ᴚᴇᴈᵺḈᵯἃἮᾝᾸ₨₸∑∏∆∂℮ⅎ₲∩∫≈≠≡≤≥⌂℗⅝⅞"
valueSpecialCharacters4 = u"⅓⅔⅛⅜⅍░▒▓■□▪▫▬▲►▼◄◊○◌●◘◙◦☺☻☼♀♂♠♣"
valueSpecialCharacters5 = u"♥♦♪♫♯ⱠⱡⱢⱣⱤⱥⱦⱧﭮצּרּﭓךּﺹﻏ﷼ﻪﻯﻴﻹ ﻼ"
sqlInsert = "INSERT INTO table (tableID, Name) VALUES (%s, %s);"
# Clean tables to make easier to see updates.
cur1.execute("DELETE FROM table")
cur2.execute("DELETE FROM table")
print "1: " + valueSpecialCharacters
args = "1", valueSpecialCharacters
cur1.execute(sqlInsert, args)
print "2: " + valueSpecialCharacters2
args = "2", valueSpecialCharacters2
cur1.execute(sqlInsert, args)
print "3: " + valueSpecialCharacters3
args = "3", valueSpecialCharacters3
cur1.execute(sqlInsert, args)
print "4: " + valueSpecialCharacters4
args = "4", valueSpecialCharacters4
cur1.execute(sqlInsert, args)
print "5: " + valueSpecialCharacters5
args = "5", valueSpecialCharacters5
cur1.execute(sqlInsert, args)
sqlSelect = "SELECT tableID, Name FROM table;"
cur1.execute(sqlSelect)
results = cur1.fetchall()
for row in results:
args = row[0], row[1]
print "args: %s", args
cur2.execute(sqlInsert, args)
# Test of deleting with utf-8
sqlDelete = "DELETE FROM table2 WHERE Name = %s;"
cur1.execute(sqlDelete, valueSpecialCharacters2)
db1.close()
db2.close()
問題是什麼?所有這些都是unicode目前你可能只是插入他們....你到目前爲止嘗試過什麼?你得到了什麼錯誤?這可能對你有幫助http://stackoverflow.com/questions/6202726/writing-utf-8-string-to-mysql-with-python – 2014-09-04 23:47:16
我已經爲別人交易了一堆錯誤。我記得的一件事是它抱怨拉丁文字。我很好奇,如果我需要將字符串解碼爲utf8或unicode,然後使用它。我仍然在玩它,我會明天看看你發送的鏈接,看看有沒有睡眠可以幫助我明天更好地發現它。 – 2014-09-05 00:07:16
具體http://stackoverflow.com/a/6203001/541038這個回答 – 2014-09-05 00:08:38