MySQLdb无法初始化字符集utf-8错误

时间:2016-06-08 17:58:27

标签: python mysql utf-8 character-encoding iso-8859-1

我正在尝试使用MySQLdb驱动程序将一些阿拉伯语单词插入</br>数据库Maria DB的arabic_word列。

我得到了hanswehr2。但在阅读之后,我发现MySQLdb驱动程序默认为latin-1 encode error,我必须在latin-1函数中明确设置utf-8作为我选择的字符集。 Sauce.

整个数据库设置为utf-8。

代码:

mariadb.connect()

但是现在我收到以下错误

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)

我已经指定Python MySQL驱动程序使用utf-8字符,但它似乎忽略了这一点。

任何意见都将受到高度赞赏。

2 个答案:

答案 0 :(得分:8)

MySQL中UTF-8的charset别名是 utf8 (没有连字符)。

有关可用的字符集,请参阅https://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html

注意,如果您需要使用非BMP Unicode点,例如emojis,请使用utf8mb4作为连接字符集和varchar类型。

答案 1 :(得分:-1)

有一种称为排序规则的东西可以帮助编码/解码特定语言的字符。 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