这可能很简单,但我无法到达那里…
如何将html代码存储在SQLITE数据库中?
我正在使用文本作为数据库中字段的数据类型(应该是blob?)
我收到奇怪的错误(并且使用相同的输入更改错误,所以我认为这与转义有关)
我的密码:
con = sqlite.connect(bd)
cur = con.cursor()
temp=cur.execute ('SELECT * from posts').fetchall()
#temp[Z][1] = ID
#temp[Z][4] = URL
i=0
while i< len (temp):
if temp[i][0]==None:
try:
html = urllib2.urlopen(str(temp[i][4])).read()
except:
html=None
#sql = 'UPDATE posts SET html = "' + str(html) + '" WHERE id = ' + str(temp[i][1])
#cur.execute( 'UPDATE posts SET html = ? WHERE id = ?' ,(html,temp[i][1]) )
cur.execute("UPDATE posts SET html = '" + str(html) + "' WHERE id = " + str(temp[i][1]))
con.commit()
print temp[i][4]
i=i+1
错误:
1-
OperationalError: near “2”: syntax
error WARNING: Failure executing file:
Python 2.6.5
(r265:79063, Apr 16 2010, 13:09:56)
Type “copyright”, “credits” or
“license” for more information.
2
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.
P.s.我宁愿如果它是文本(人类可读)而不是blob,但是如果这是更简单的方法,我全力以赴.
谢谢
解决方法:
尝试:
cur.execute(
"UPDATE posts SET html = ? WHERE id = ?", (html ,temp[i][1]))
使用参数化的参数允许sqlite3为您转义引号. (这也有助于防止SQL injection.)
关于ProgrammingError:html应该是unicode对象,而不是字符串对象.当您打开网址时:
response=urllib2.urlopen(str(temp[i][4]))
查看内容类型标题:
content_type=response.headers.getheader('Content-Type')
print(content_type)
可能会说类似
'text/html; charset=utf-8'
在这种情况下,您应该使用utf-8编解码器解码html字符串:
html = response.read().decode('utf-8')
这将使html成为unicode对象,并(希望)解决ProgrammingError.
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!