jeudi 21 avril 2016

Python: How to query utf-8 string from sqlite database

I'm trying to insert Arabic words in Sqlite database then query these words. What I'm facing is the result back to me like this : ('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)

so here is simple code explain for what I'm doing :

# 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

In this example I create test table with one value title I insert to title Arabic word then when I'm trying to query this word and write it to file show to me this : ('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)

How can I fix it ?

Aucun commentaire:

Enregistrer un commentaire