2010-12-18 66 views
3

这可能是很简单,但我不能让那里...我如何保存HTML在DB(SQLITE PYTHON)

我如何可以存储HTML代码在一个SQLite数据库?

我用文字作为DB数据类型的字段(它应该是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,但如果它是更简单的方式,我都是为了它。

感谢名单

回答

3

尝试:

cur.execute(
    "UPDATE posts SET html = ? WHERE id = ?", (html ,temp[i][1])) 

使用参数化的参数,可以sqlite3的逃脱报价为您服务。 (这也有助于防止SQL injection。)

关于ProgrammingError:html应该是一个unicode对象,而不是一个string对象。当您打开的网址:

response=urllib2.urlopen(str(temp[i][4])) 

看内容类型头:

content_type=response.headers.getheader('Content-Type') 
print(content_type) 

它可能会说

'text/html; charset=utf-8' 

在这种情况下,你应该解码html串与utf-8编解码器:

html = response.read().decode('utf-8') 

这会使html成为一个unicode对象,并且(希望)可以解决ProgrammingError的问题。

+1

100%正确。 Namaste我的朋友或我向你鞠躬。谢谢 – 2010-12-18 21:48:23