有没有任何方法可以使用sqllite数据库中列表中的值



这个项目的目标是从一个表中提取数据,并将结果放入sqllite数据库中,但我不知道我目前尝试的方法是否可行。目前,数据存储在一个由表上的每一行分隔的列表中,唯一的问题是试图将其插入数据库。我在这段代码中发现的错误是sql插入的不完整输入。我试着在网上搜索解决方案,但到目前为止没有任何帮助,这要么会导致这个问题,要么会导致列表索引超出范围。

from bs4 import BeautifulSoup
import requests
import sqlite3
headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"}
url = "https://en.wikipedia.org/wiki/Comparison_of_computer_viruses"
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[1]
rows = table.find_all('tr')
row_list= list()
for tr in rows:
td = tr.find_all('td')
row = [i.text for i in td]
row_list.append(row)
print(row_list)
print(row_list[1][1])
maldb = sqlite3.connect("maldb")
cursor = maldb.cursor()
cursor.execute('''drop table if exists mal''')
cursor.execute('''create table mal
(virus text primary key,
alias text,
typeof text,
subtype text,
isolation_date text,
isolation text,
origin text,
author text,
notes text)
''')
for z in range(1,95):
cursor.execute('''INSERT into mal ('?','?','?','?','?','?','?','?','?')''',(row_list[z][0],row_list[z][1],row_list[z][2],row_list[z][3],row_list[z][4],row_list[z][5],row_list[z][6],row_list[z][7],row_list[z][8]))
maldb.commit()
maldb.close()

这里有不同的问题。第一个是你的语法不正确:你不应该引用?字符,所以至少你的查询应该是:

cursor.execute('''INSERT into mal (?,?,?,?,?,?,?,?,?)''',(row_list[z][0],row_list[z][1],row_list[z][2],row_list[z][3],row_list[z][4],row_list[z][5],row_list[z][6],row_list[z][7],row_list[z][8]))

更糟糕的是,有些行没有9项(第一行没有,另一行只有8项(,所以您应该检查一下。最后,最好使用在execute上循环的executemany,因为查询只编译一次。所以我建议:

cursor.executemany('''INSERT into mal values(?,?,?,?,?,?,?,?,?)''',
[row for row in row_list if len(row) == 9])

最后,您不应该为virus列使用PRIMARY KEY属性,因为该列表实际上包含'Jerusalemn'的副本,而主键必须是唯一的。

很少有东西:

  1. 语法不正确:您需要
  2. 您正在将"病毒"值设置为主键,但'Jerusalem'在其中出现了两次。不能有超过1行的值与主键相同
  3. 我只想使用panda来解析html<table>标签
  4. 虽然您可以迭代每一行来添加它,但也有一种方法可以使用executemany()方法同时写入多行/所有行。请参阅此处

代码:

import sqlite3
import pandas as pd
table = pd.read_html("https://en.wikipedia.org/wiki/Comparison_of_computer_viruses")[1]
maldb = sqlite3.connect("maldb.db")
cursor = maldb.cursor()
cursor.execute('''drop table if exists mal''')
cursor.execute('''create table mal
(virus text primary key,
alias text,
typeof text,
subtype text,
isolation_date text,
isolation text,
origin text,
author text,
notes text)
''')
for idx, row in table.iterrows():
try:
sql = "INSERT INTO mal (virus, alias, typeof, subtype, isolation_date, isolation, origin, author, notes ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
val = (row['Virus'],row['Alias(es)'],row['Types'],row['Subtype'],row['Isolation Date'],row['Isolation'],row['Origin'],row['Author'],row['Notes'])
cursor.execute(sql, val)
except Exception as e:
print (e)
print (val)
maldb.commit()
maldb.close()

最新更新