我试图从刮取的文本构建SQLite数据库。数据库中的每一行对应于从列表中获取的字符串,并且对于每个循环创建另一列并使用新的字符串数据填充。SQLite/python - 在while循环内添加数据列
conn = sqlite3.connect('data.sqlite')
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS Data;
CREATE TABLE Data(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
words text)''')
while True
url = 'www.xyz.com'
if url == "break": break
#parse - find tag of interest
html = urllib.request.urlopen(url)
p_s = BeautifulSoup(html,'html.parser')
words = str(p_s.findAll('p',{'id':'p-5'}))
words = strip_tags(words)
words = pd.DataFrame(words)
col_number = col_number + 1
col_name = ('Group', col_number)
cur.execute('''ALTER TABLE Data ADD ? TEXT''', (col_name,))
for i,j in words.iterrows():
cur.execute('''INSERT OR IGNORE INTO Data (col_name)
VALUES (?)''',(j))
conn.commit()
当我运行这段代码,我得到:
sqlite3.Operational.Error : near "?": syntax error
我要去哪里错了?谢谢,我为我的草率代码道歉,我是Python的新手!
添加新的数据作为栏目是可怕的设计。将“新字符串数据”添加为新行,而不是新列。使用** 1 **附加列'Group'来保存'col_name'的值。使用结果会容易得多。 – alexis