从Python代码向SQLite数据库插入字符串时出错
当我想把一个字符串从 Python
代码插入到 SQLite
数据库时,出现了这个错误:
sqlite3.ProgrammingError: 你不能使用8位字节字符串,除非你使用一个可以解释8位字节字符串的text_factory(比如text_factory = str)。强烈建议你直接把应用程序切换到使用Unicode字符串。
这是插入语句:
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' 编解码器无法解码位置44的字节0xc3:序数不在范围(128)内
谢谢
2 个回答
3
SQLite只存储Unicode字符串。很可能是你的URL不是Unicode格式,所以你需要把它转换一下。
你也可以把URL当作二进制数据(blob)存储,不过这样以后会让事情变得更复杂。
1
虽然对于一个网址来说,使用Unicode并不是绝对必要的,但你可以选择这样做。
BeautifulSoup
可以处理Unicode格式。
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""<a href="ascii">""", fromEncoding="utf-8")
>>> isinstance(soup('a', href=True)[0]['href'], unicode)
True
>>> soup = BeautifulSoup("""<a href="αβγ">""", fromEncoding="utf-8")
>>> soup('a', href=True)[0]['href']
u'\u03b1\u03b2\u03b3'
在这两种情况下,网址都是unicode
格式。
你可以使用isinstance()
或者type()
来检查这个网址的类型。
你可以设置encoding=None
来获取Unicode格式:
i.renderContents(encoding=None)
一般来说,在交互式的Python控制台中使用dir(obj)
和help(obj.method)
会很有帮助。你也可以查看打印文档的相关内容。