2015-12-03 105 views
1

我有一个阿拉伯语的字符串说如何使用python在mysql数据库中存储阿拉伯语文本?

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

我想写这个阿拉伯文字转换成MySQL数据库。我试着用

txt = smart_str(txt) 

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

这两个din't工作,因为他们coverted的字符串

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; 

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

也并从MySQL数据库这个阿拉伯文字的快速导出写同样的阿拉伯语文本文件或将再次将其转换回为Unicode?

我用foolowing代码中插入

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”是允许的。

+0

你能告诉我们你用来执行INSERT的代码吗? –

+0

我已经包含了插入。请帮助 – kkoe

回答

1

为了澄清一些事情,因为它会帮助你一起在未来也是如此。

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

这不是阿拉伯字符串。这是一个unicode 对象,带有unicode码点。如果你简单地打印出来,如果你的终端支持阿拉伯语,你会得到的输出是这样的:

>>> 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) 

那是什么告诉你的是,一些数在表格latin-1中不存在unicode对象,所以程序不知道如何将其转换为字节。

计算机存储字节。因此,当存储或传输信息时,您需要始终正确编码/解码。

这个编码/解码步骤有时被称为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从支持阿拉伯语一个终端或应用程序;否则 - 即使它正确插入,当它被程序显示时 - 你将看到垃圾字符。

+0

谢谢你,先生。这非常有教育意义。万分感谢:) – kkoe

2

只需执行SET names utf8执行你的INSERT前:

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,你应该阅读。

+0

嗨,先生,感谢您的重播,因为我前面提到的,我可以看到我的数据库中UTF-8文本但UTF-8文本不是阿拉伯语。 – kkoe

+0

当我用smart_str()则转换\ u0627 \这是阿拉伯语\ XD8 \别的 – kkoe

+0

只需插入原始的阿拉伯语。无需将其转换为Unicode。 –