我试图使用MySQLdb驱动程序将一些阿拉伯语单词插入我的arabic_word
数据库Maria DB的hanswehr2
列中。
我得到了一个latin-1 encode error
。但在阅读之后,我发现MySQLdb驱动程序默认为latin-1
,我必须在utf-8
函数中明确设置mariadb.connect()
作为我选择的字符集。 Sauce.
整个数据库设置为utf-8。
码:
def insert_into_db(arabic_word, definition):
try:
conn = mariadb.connect('localhost', 'root', 'xyz1234passwd', 'hans_wehr', charset='utf-8', use_unicode=True)
conn.autocommit(True)
cur = conn.cursor()
cur.execute("INSERT INTO hanswehr2 (arabic_word , definition) VALUES (%s,%s)", (arabic_word, definition,))
except mariadb.Error, e:
print e
sys.exit(1)
但是现在我收到以下错误:
/usr/bin/python2.7 /home/heisenberg/hans_wehr/main.py
Total lines 87672
(2019, "Can't initialize character set utf-8 (path: /usr/share/mysql/charsets/)")
Process finished with exit code 1
我已经指定Python MySQL驱动程序使用utf-8字符,但它似乎忽略了这一点。
任何投入都将受到高度赞赏。
MySQL中UTF-8的charset别名是utf8
(没有连字符)。
有关可用的字符集,请参阅https://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html。
注意,如果需要使用非BMP Unicode点,例如emojis,请使用utf8mb4
作为连接字符集和varchar类型。
有一种称为排序规则的东西可以帮助编码/解码特定语言的字符。 https://softwareengineering.stackexchange.com/questions/95048/what-is-the-difference-between-collation-and-character-set
我想你需要在创建数据库表或连接字符串时指定它。请参考:store arabic in SQL database
更多关于python mysql连接:https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-set-charset-collation.html