私はSqliteデータベースにアラビア語を挿入しようとしています。 このように私が直面してることは私に戻って結果である:('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)
Python:sqliteデータベースからutf-8文字列を照会する方法
ので、ここでは簡単なコードですが、私がやっている何のために説明します。この例では
# 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
を私は1つの値でテストテーブルを作成しますタイトル 私はタイトルにアラビア語を挿入し、この単語をクエリしてファイルに書き出すときにこれを表示します:('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)
どうすれば修正できますか?
[ 'リロード(SYS)を使用しない.setdefaultencoding( "UTF-8")'](http://stackoverflow.com/q/3828723/4279) – jfs
@JFSebastian同じこと固定されていません私の問題 –
あなたのコードに複数の問題があります。 – jfs