我试图在sqlite数据库中插入阿拉伯语单词,然后查询这些单词。
我面对的是这样的结果:('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)
下面是一些简单的代码解释:

# coding: utf-8

import sys; reload(sys).setdefaultencoding("utf-8")

import sqlite3

class Database(object):

    def execute_db(self, *args):
        db = sqlite3.connect("sqlite3.db")
        db.text_factory = str
        cur = db.cursor()
        data = True
        try:
            args = list(args)
            args[0] = args[0].replace("%s", "?")
            args = tuple(args)
            cur.execute(*args)
            arg = args[0].split()[0].lower()
            if arg in ["update", "insert", "delete", "create"]: db.commit()
        except Exception, data:
            data = False
            db.rollback()
        db.commit()
        db.close()
        return data

    def fetch_one(self, *args):
        db = sqlite3.connect("sqlite3.db")
        db.text_factory = str
        try: cur = db.cursor()
        except: return None
        data = None
        try:
            args = list(args)
            args[0] = args[0].replace("%s", "?")
            args = tuple(args)
            cur.execute(*args)
            try: data = cur.fetchone()
            except Exception, data: data = None
        except Exception, data:
            data = None
            db.rollback()
        db.close()
        return data


class Start(Database):
    def __init__(self):
        self.execute_db("create table test(title text)")
        self.execute_db("insert into test(title) values(%s)", ("مرحباً",))

        self.write_query_into_file()

    def write_query_into_file(self):
        f = open("test.txt", "w+")
        f.write(str(self.fetch_one("select title from test")))
        f.close()

try: Start()
except Exception as why: print why

在这个例子中,我用一个值标题创建测试表
我插入标题阿拉伯语单词,然后当我试图查询这个单词并将其写入文件时,显示给我这个:('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)
我怎样才能修好它?

最佳答案

使用unicodetype,在python中表示文本。不要对unicode字符串调用str()(在python 2中str()转换为字节)。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import io
import sqlite3

# insert Unicode into SQLite db
conn = sqlite3.connect(':memory:')
conn.execute("create table test(title text)")
conn.execute("insert into test(title) values(?)", ("مرحباً",))

# print titles to file as text in utf-8 encoding
with io.open('utf-8.txt', 'w', encoding='utf-8') as file:
    for title, in conn.execute("select title from test"):
        print(title, file=file)

10-04 19:07