2010-12-18 45 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