使用 python 中的链接填充 sqlite3 数据库

populating sqlite3 db with links in python

我正在尝试使用包含字符串列表 (links) 的单个列来填充数据库。我抓取了列表,我必须在将它发送到数据库之前修改每个 link。这是代码:

for event in events:
    link_url = "https://www.website.com"+event+"#all"
    c.execute("INSERT INTO table (links) VALUES(?)", link_url)

如果我修改变量并发送一个元组,我可以让它工作,就像这样:

for event in events:
    link_url = "https://www.website.com"+event+"#all"
    link = (link_url,)
    c.execute("INSERT INTO seriea (links) VALUES(?)", link_url)

但我不想使用此解决方案,因为我想稍后返回一个字符串列表:

c = connection.execute('select links from table')
list_of_urls = c.fetchall()

但这给了我一个元组列表。

这是我遇到的错误:ProgrammingError:提供的绑定数量不正确。当前语句使用1个,提供80个

我认为这是因为字符串字符被计算在内(实际上更多,但我注意到“供应”之前的数字随着 link 的变化而变化)

I don't want to use this solution since I want to get a list of strings back out later:

c = connection.execute('select links from table')
list_of_urls = c.fetchall()

But this gives me a list of tuples.

当您执行 select 时获得的元组列表与您插入数据的方式无关。请记住,table 有两个维度:

id links something else
1 "foo" "bar" "baz"
2 "quux" "herp" "derp"

当您执行 select 时,您会得到一个与此处的行相对应的列表。但是每一行都有多个字段:idlinkssomethingelse。列表中的每个元组都包含 table.

中每个字段的值

如果您只想将 URL 作为字符串列表,您可以使用列表理解或类似的方法:

c = connection.execute('select links from table')
list_of_rows = c.fetchall()
list_of_strings = [row[0] for row in list_of_rows]
#                      ^ index of first element in
#                  ^^^ the tuple of values for each row

请注意,插入数据时必须提供元组或其他序列:

For the qmark style, parameters must be a sequence. For the named style, it can be either a sequence or dict instance. The length of the sequence must match the number of placeholders, or a ProgrammingError is raised. If a dict is given, it must contain keys for all named parameters.

您可能以错误的方式考虑了其中的元组部分。不需要传入一个url的元组,需要传入一个参数的元组。你不是说“链接列应该包含这个元组”而是“这个元组包含足够的值来填充这个查询中的占位符”。

我会这样重写:

for event in events:
    link_url = "https://www.website.com"+event+"#all"
    c.execute("INSERT INTO seriea (links) VALUES(?)", (link_url,))

这样你就可以有多个参数,例如

c.execute(
    "INSERT INTO seriea (links, some, other) VALUES(?, ?, ?)",
    (link_url, foo, bar),
)

The current statement uses 1, and there are 80 supplied.

I think that's because the string characters are counted

是的,这很可能是正在发生的事情。 c.execute()期望收到一个序列,字符串是一个字符序列。