【问题标题】:How can I store HTML in a DB (SQLITE PYTHON)如何将 HTML 存储在数据库中(SQLITE PYTHON)
【发布时间】:2010-12-18 00:18:10
【问题描述】:

这可能很简单,但我无法到达那里......

如何在 SQLITE 数据库中存储 html 代码?

我使用文本作为数据库中字段的数据类型(应该是 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:接近“2”:语法 错误警告:执行文件失败: Python 2.6.5 (r265:79063,2010 年 4 月 16 日,13:09:56) 输入“版权”、“学分”或 “许可证”了解更多信息。

2-

ProgrammingError: 你不能使用 8 位字节串,除非你使用 可以解释 8 位的 text_factory 字节串(如 text_factory = str)。 强烈建议您 相反,只需切换您的应用程序 到 Unicode 字符串。

附:我宁愿如果它是文本(人类可读)而不是 blob,但如果它是更简单的方法,我完全赞成。

感谢

【问题讨论】:

    标签: python html database sqlite


    【解决方案1】:

    试试:

    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'
    

    在这种情况下,您应该使用utf-8 编解码器解码html 字符串:

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

    这将使html 成为一个unicode 对象,并且(希望)寻址ProgrammingError。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      相关资源
      最近更新 更多