我需要一些幫助,我創建了一個帶有列的數據庫,以允許我將字符串列表存儲在數據庫中。現在我想將數據插入到數據庫中,但它只會將數據存儲在按鈕表中,而不是存儲在程序表中。在sqlite3數據庫中插入數據
當我試試這個:
cur = con.cursor()
cur.execute('CREATE TABLE programs(channel TEXT, title TEXT, start_date TIMESTAMP, stop_date TIMESTAMP, button_id TEXT, description TEXT)')
con.commit()
for program in channel.findall('programme'):
cur.execute("INSERT INTO programs(channel, title, start_date, stop_date)" + " VALUES(?, ?, ?, ?)", [channel_name, title, start_time, stop_time])
programs_id = list()
for elem in program_button:
programs_id.append(elem.getId())
programs_id = map(str, programs_id)
#store the id and width of buttons in a database
for ids, width in zip(programs_id, program_width):
cur.execute("INSERT INTO buttons(button_ids, button_width)" + " VALUES(?, ?)", [ids, width])
cur.execute("INSERT INTO programs(button_id)" + " VALUES(?)", [ids])
con.commit()
cur.close()
我要插入的數據ids
在節目表中的列button_id
,但是當我嘗試它什麼事都沒有發生。
你能幫我解釋一下如何在程序表中插入數據嗎?
編輯:當我嘗試這樣:
for ids, width in zip(programs_id, program_width):
cur.execute("UPDATE programs SET button_id = ? WHERE title=?", ([ids, title]))
這將存儲在錯誤的行中的數據。
#yields:
#channel | title | start_date | stop_date | button_id | description
###########################################################################
#BBC One | Tomorrow's Food | '2015-01-01'|'2016-01-01'| 3003 | blank
#BBC One | BBC News at Ten | '2015-01-01'|'2016-01-01'| 3056 | blank
#BBC One | South E Today | '2015-01-01'|'2016-01-01'| 3125 | blank
#BBC One | A Question of S | '2015-01-01'|'2016-01-01'| 3006 | blank
#BBC One | Film 2016 | '2015-01-01'|'2016-01-01'| 3007 | blank
它應該是這樣的:
#yields:
#channel | title | start_date | stop_date | button_id | description
###########################################################################
#BBC One | Tomorrow's Food | '2015-01-01'|'2016-01-01'| 3003 | blank
#BBC One | BBC News at Ten | '2015-01-01'|'2016-01-01'| 3004 | blank
#BBC One | South E Today | '2015-01-01'|'2016-01-01'| 3005 | blank
#BBC One | A Question of S | '2015-01-01'|'2016-01-01'| 3006 | blank
#BBC One | Film 2016 | '2015-01-01'|'2016-01-01'| 3007 | blank
非常感謝你,但是當我嘗試這個'cur.execute(「UPDATE programs SET button_id =?」,([ids]))'時,它會更新數據庫中每行的相同數據。我如何更新表中的數據而不用重複,因爲我在循環中使用它們? – Rob
看看答案的底部,我改變它以反映你的評論。主要問題是我認爲更新SQL命令中的'WHERE'子句。 –
我不認爲你明白我想說。請在我的問題的底部看到我已編輯,所以你會看到數據'button_id'已經更新了錯誤的行,它應該已經在每行更新而不會弄亂它。 – Rob