gpt4 book ai didi

python - 从 Python 代码将字符串插入 SQLite 数据库时出错

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:24 25 4
gpt4 key购买 nike

当我想从 Python 代码中插入一个字符串到 SQLite 数据库时,我得到了这个错误:

sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

这是插入语句:

cur.execute("insert into links (url, title, ...) values (:url, :title, ...)", locals())

字符串是这样产生的:

soup = BeautifulSoup(html.read(), fromEncoding="utf-8")
html.close()
for i in soup.findAll('a'):
url = i['href']
title = i.renderContents()

你能告诉我如何将字符串插入 SQLite 数据库吗?

编辑:我发现 url 字符串在插入到另一个表时是可以的。 url 字符串的类型是 unicode。问题是插入 title 字符串时。 title 字符串的类型是str

我试过:

title = unicode(i.renderContents())

但这以错误结束:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 44: ordinal not in range(128)

谢谢

最佳答案

SQLite 只存储 unicode 字符串。该 URL 很可能不是 unicode,因此您需要对其进行转换。

您可以将 URL 存储为 blob(二进制),但这会使以后的生活变得更加复杂。

关于python - 从 Python 代码将字符串插入 SQLite 数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7893305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com