我有一个 sqlite3 数据库,其中第一列是
id
并设置为主键并自动递增。我正在尝试从我的 python 字典中插入值,如下所示:
value = {'host': [], 'drive': [], 'percent': []}
soup = bs(contents, 'html.parser')
for name in soup.find_all("td", class_="qqp0_c0"):
hostname = name.parent.find('td').get_text()
drive = name.parent.find('td', class_="qqp0_c1").get_text()
used_percent = name.parent.find('td', class_="qqp0_c5").get_text()
value['host'].append(hostname)
value['drive'].append(drive)
value['percent'].append(used_percent)
#cur.executemany("INSERT INTO scrap VALUES (?, ?, ?)", hostname, drive, used_percent)
cur.execute("INSERT INTO scrap VALUES (?, ?, ?);", value)
我不断收到错误,我最新的错误似乎意味着它需要一个
id
值:
cur.execute("INSERT INTO scrap VALUES (?, ?, ?);", value) sqlite3.OperationalError:表废料有 4 列,但提供了 3 个值
我需要提供
id
号码吗?
这是数据库架构:
CREATE TABLE scrap (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hostname VARCHAR(255),
drive VARCHAR(255),
perc VARCHAR(255)
);
如果
id
列自动递增,则无需为其提供值,但您确实需要“告诉”数据库您没有插入它。请注意,为了绑定字典,您需要按名称指定占位符:
cur.execute("INSERT INTO scrap (hostname, drive, perc) VALUES (:host, :drive, :percent);", value)
编辑:
跟进评论中的讨论 -
value
字典应该将占位符名称映射到其预期值,而不是包含它们的列表:
soup = bs(contents, 'html.parser')
for name in soup.find_all("td", class_="qqp0_c0"):
hostname = name.parent.find('td').get_text()
drive = name.parent.find('td', class_="qqp0_c1").get_text()
used_percent = name.parent.find('td', class_="qqp0_c5").get_text()
value = {'host': hostname, 'drive': drive, 'percent': used_percent}
cur.execute("INSERT INTO scrap (hostname, drive, perc) VALUES (:host, :drive, :percent);", value)