如何使用 python 在 mysql 数据库中存储阿拉伯语文本?

How to store arabic text in mysql database using python?

我有一个阿拉伯字符串说

txt = u'Arabic (\u0627\u0644\u0637\u064a\u0631\u0627\u0646)'

我想将这段阿拉伯语文字转换成mySql数据库。我尝试使用

txt = smart_str(txt)

txt = text.encode('utf-8') 

这两个都不起作用,因为它们将字符串转换为

u'Arabic (\xd8\xa7\xd9\x84\xd8\xb7\xd9\x8a\xd8\xb1\xd8\xa7\xd9\x86)' 

另外我的数据库字符集已经设置为utf-8

ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;

因此,由于这个新的 unicode,我的数据库正在显示与编码文本相关的字符。请帮忙。我希望保留我的阿拉伯语文本。

从 MySQL 数据库快速导出此阿拉伯语文本是否会将相同的阿拉伯语文本写入文件,或者它会再次将其转换回 unicode?

我是用傻瓜代码插入的

cur.execute("INSERT INTO tab1(id, username, text, created_at) VALUES (%s, %s, %s, %s)", (smart_str(id), smart_str(user_name), smart_str(text), date))

早些时候,当我没有使用 smart_str 时,它会抛出一个错误,指出只允许使用 'latin-1'。

只需在执行 INSERT:

之前执行 SET names utf8
cur.execute("set names utf8;")

cur.execute("INSERT INTO tab1(id, username, text, created_at) VALUES (%s, %s, %s, %s)", (smart_str(id), smart_str(user_name), smart_str(text), date))

您的问题与 this SO post 非常相似,您应该阅读一下。

澄清一些事情,因为这对你以后也有帮助。

txt = u'Arabic (\u0627\u0644\u0637\u064a\u0631\u0627\u0646)'

这不是阿拉伯字符串。这是一个带有 unicode 代码点的 unicode object。如果您只是打印它,并且您的终端支持阿拉伯语,您将得到如下输出:

>>> txt = u'Arabic (\u0627\u0644\u0637\u064a\u0631\u0627\u0646)'
>>> print(txt)
Arabic (الطيران)

现在,要在数据库中获得与 Arabic (الطيران) 相同的输出,您需要对字符串进行编码。

编码正在使用这些代码点;并将它们转换为字节,以便计算机知道如何处理它们。

所以最常见的编码是utf-8,因为它支持英文的所有字符,加上很多其他语言(包括阿拉伯语)。还有其他的,例如 windows-1256 也支持阿拉伯语。有些没有这些数字的引用(称为代码点),当你尝试编码时,你会得到这样的错误:

>>> print(txt.encode('latin-1'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 8-14: ordinal not in range(256)

告诉你的是 table latin-1 中不存在 unicode 对象中的某些数字,因此程序不知道如何将其转换为字节。

计算机存储字节。因此,在存储或传输信息时,您需要始终 encode/decode 正确。

这个 encode/decode 步骤有时称为 unicode sandwich - 外面的一切都是字节,里面的一切都是 unicode。


除此之外,您需要在将数据发送到数据库之前对其进行正确编码;为此,对其进行编码:

q = u"""
    INSERT INTO
       tab1(id, username, text, created_at)
    VALUES (%s, %s, %s, %s)"""

conn = MySQLdb.connect(host="localhost",
                       user='root',
                       password='',
                       db='',
                       charset='utf8',
                       init_command='SET NAMES UTF8')
cur = conn.cursor()
cur.execute(q, (id.encode('utf-8'),
                user_name.encode('utf-8'),
                text.encode('utf-8'), date))

要确认它是否被正确插入,请确保您从支持阿拉伯语的终端或应用程序使用 mysql;否则 - 即使它正确插入,当它被你的程序显示时 - 你会看到乱码。