SQLite / python - 在while循环中添加包含数据的列

时间:2017-07-14 18:31:47

标签: python sqlite web-scraping

我正在尝试从拼写文本构建SQLite数据库。数据库中的每一行对应于从列表中获取的字符串,对于每个循环,将创建另一列并使用新的字符串数据填充该列。

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 个答案:

答案 0 :(得分:0)

更改为:

    cur.execute('''ALTER TABLE Data ADD {} TEXT'''.format('Group ' + str(col_number)))
    for i,j in words.iterrows():
        cur.execute('''INSERT OR IGNORE INTO Data ({})
        VALUES (?)'''.format(col_name), (j,))
    conn.commit()

cur.execute('''ALTER TABLE Data ADD {} TEXT'''.format('Group ' + str(col_number)))
        for i,j in words.iterrows():
            cur.execute('''INSERT OR IGNORE INTO Data {}
            VALUES (?)'''.format(col_name), (j,))
        conn.commit()

其中一个应该工作