【问题标题】:python and sqlite3.ProgrammingError on inserting utf-8 stringpython 和 sqlite3.ProgrammingError 插入 utf-8 字符串
【发布时间】:2015-03-05 19:52:06
【问题描述】:

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

sqlite3.ProgrammingError: 你不能使用 8 位字节串,除非你使用可以解释 8 位字节串的 text_factory(比如 text_factory = str)。强烈建议您将应用程序切换为 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') 将其分配给类字段。我还需要做什么? :-/

提前致谢。

【问题讨论】:

    标签: python encoding utf-8 sqlite


    【解决方案1】:

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

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

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

    希望对你有帮助。

    【讨论】:

    • 就是这样,con.execute(... vlasnik.ime().decode('utf-8') ...),这就是我错过的。谢谢!
    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 2015-06-02
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2011-09-06
    相关资源
    最近更新 更多