python 和 sqlite3.ProgrammingError 关于插入 utf-8 字符串

python and sqlite3.ProgrammingError on inserting utf-8 string

我试图插入一个 utf-8 字符串,但我得到:

sqlite3.ProgrammingError:除非使用可以解释 8 位字节串的 text_factory(如 text_factory = str),否则不得使用 8 位字节串。强烈建议您将应用程序切换到 Unicode 字符串。

Here is the whole module。以下是代码的相关部分:

########### reading json from a utf-8 file:
        with open(file_name) as f:
            return json.loads(f.read())
########### feeding utf-8 encoded text to constructor
    for obveznik in json:
        vlasnici[obveznik["id_obveznik"]] = Vlasnik(obveznik["id_obveznik"], obveznik["naziv"].encode('utf-8'))
########### constructor simply assigns
class Vlasnik
    def __init__(self, id, ime):
        self._id = id
        self._ime = ime
########### here's a getter in the same class:
    def ime(self):
        return self._ime
########### and then I use the getter
                        cur.execute("INSERT INTO indeksi VALUES(?, ?, ?, ?, ?, ?)", (
# [...]
                            vlasnik.ime(),
# [...]
                        ))
########################

我在 cur.execute() 上得到了 sqlite3.ProgrammingError。我读取了字符串 frmo utf-8 文件并使用 .encode('utf-8') 将其分配给 class 字段。我还需要做什么? :-/

提前致谢。

如果您的字符串已经是 UTF-8 则不要使用 encode,直接传递它而不进行处理。如果不是,请使用 .decode("utf-8").

使用 Python 2.x 时请考虑始终使用 unicode 字符串。当涉及文件 IO 时,请考虑使用 io 模块而不是内置的 open 函数,它可以让您指示特定的编码。

import io
f = open("file.txt", enconding="utf-8")

希望对您有所帮助。