【问题标题】:Update Sqlite w/ Python: InterfaceError: Error binding parameter 0 and None Type is not subscriptable使用 Python 更新 Sqlite:InterfaceError:错误绑定参数 0 和 None 类型不可下标
【发布时间】:2019-04-09 17:25:39
【问题描述】:

我已经抓取了一些网站并将 html 信息存储在 sqlite 数据库中。现在,我想提取和存储电子邮件地址。我能够成功提取并打印 id 和电子邮件。但是,当我尝试使用这些新的电子邮件地址更新数据库时,我不断收到 TypeError: "'NoneType' object is not subscriptable" 和 "sqlite3.InterfaceError: Error binding parameter 0 - possible unsupported type"。

我已验证我在更新语句中使用的数据类型与我的数据库相同(id 是 int 类,email 是 str)。我在谷歌上搜索了一堆不同的例子,并且对语法进行了很多研究。

我还尝试删除更新语句中的 Where 子句,但得到了相同的错误。

import sqlite3
import re


conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()

x = cur.execute('SELECT id, html FROM Pages WHERE html is NOT NULL and email is NULL ORDER BY RANDOM()').fetchone()
#print(x)#for testing purposes

for row in x:
    row = cur.fetchone()
    id = row[0]
    html = row[1]

    email = re.findall(b'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', html)
    #print(email)#testing purposes
    if not email:
        email = 'no email found'

    print(id, email)
    cur.execute('''UPDATE pages SET email = ? WHERE id = ? ''', (email, id))


conn.commit

我希望更新语句使用为相应行提取的电子邮件地址更新数据库。

【问题讨论】:

  • 请在问题正文中包含异常的完整回溯。此外,您能否将数据缩减为产生问题的单行并提供 idhtml 值?

标签: python-3.x sqlite


【解决方案1】:

这里发生了一些事情。

首先,你不想这样做:

for row in x:
    row = cur.fetchone()

如果你想遍历查询返回的结果,你应该考虑这样的事情:

for row in cur.fetchall():
    id = row[0]
    html = row[1]
    # ...

要了解您看到的其余错误,让我们一步一步看一下。

TypeError:“'NoneType' 对象不可下标”:

这很可能在这里生成:

row = cur.fetchone()
id = row[0]

Cursor.fetchone 返回None 如果执行的查询不匹配任何行或结果集中没有剩余行。然后,下一行尝试执行None[0],这会引发相关错误。

sqlite3.InterfaceError:错误绑定参数 0 - 可能是不支持的类型:

re.findall 返回非重叠匹配的列表,而不是单个匹配。不支持将 Python 列表绑定到 sqlite3 文本列类型。要解决此问题,您需要从匹配列表中获取第一个元素(如果存在),然后将其作为电子邮件参数传递给 UPDATE。

【讨论】:

【解决方案2】:

.findall() 返回一个列表。 您想遍历该列表:

    for email in re.findall(..., str(html)):
        print(id, email)
        cur.execute(...)

不确定b'[a-z...' 表达式发生了什么。 建议您改用原始字符串:r'[a-z...'。 它可以很好地处理正则表达式\ backwhacks。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    相关资源
    最近更新 更多