Python: How to query utf-8 string from sqlite database -
i'm trying insert arabic words in sqlite database query these words. i'm facing result me : ('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)
so here simple code explain 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 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 test"))) f.close() try: start() except exception why: print why
in example create test table 1 value title insert title arabic word when i'm trying query word , write file show me : ('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b',)
how can fix ?
use unicode
type, represent text in python. not call str()
on unicode string (str()
converts bytes on python 2).
#!/usr/bin/env python # -*- coding: utf-8 -*- __future__ import unicode_literals __future__ import print_function import io import sqlite3 # insert unicode sqlite db conn = sqlite3.connect(':memory:') conn.execute("create table test(title text)") conn.execute("insert test(title) values(?)", ("مرحباً",)) # print titles file text in utf-8 encoding io.open('utf-8.txt', 'w', encoding='utf-8') file: title, in conn.execute("select title test"): print(title, file=file)
Comments
Post a Comment