python和sqlite3.programming插入utf8字符串时出错

2024-10-03 06:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

sqlite3.ProgrammingError:除非使用可以解释8位bytestrings的文本工厂(如text_factory=str),否则不能使用8位bytestrings。强烈建议您将应用程序切换为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(),
# [...]
                        ))
########################

我得到了sqlite3.ProgrammingError当前执行(). 我读取了字符串frmo utf-8文件,并使用.encode('utf-8')将其分配给一个类字段。我还要做什么?:-/

提前谢谢。在


Tags: the字符串textselfidjsonreturnsqlite3
1条回答
网友
1楼 · 发布于 2024-10-03 06:30:22

如果您的字符串已经是UTF-8,那么不要使用encode,只需传递它而不进行处理。如果没有,请使用.decode("utf-8")。在

使用Python2.x时,请考虑始终使用unicode字符串。当涉及到文件IO时,请考虑使用^{}模块,而不是内置的open函数,该函数允许您指示特定的编码。在

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

希望有帮助。在

相关问题 更多 >