2017-04-24 38 views
1

我知道這是一個愚蠢的問題,但你是如何更新一列通過匹配它的關鍵在sqlite,我試着這個方法,但我一直沒有得到匹配,我知道鍵應該匹配,因爲我從數據庫中獲得它們。我究竟做錯了什麼?更新Sqlite3 colomn,鍵匹配問題

c.execute('''SELECT ROUND(AVG(ft.score), 2), st.subreddit_id 
     FROM posts as ft JOIN subreddits as st ON st.subreddit_id == ft.subreddit_id 
     GROUP BY 2 
     ORDER BY 2 desc 
     ''') 

average = [] 
for rows in c.fetchall(): 
    average.append(rows) 

for index in average: 
    start = time.time() 
    print(index) 
    try: 
     c.execute('''UPDATE subreddits SET average_score = ''' + str(index[0]) + ''' WHERE ''' + str(index[1]) + ''' == subreddit_id;''') 
     print(str(index[1])) 
    except sqlite3.OperationalError: 
     print('{} not found'.format(index)) 

回答

1

您應該將參數作爲第二個參數傳遞給.execute()以允許sqlite3執行正確的轉義。您也有語法錯誤==。試試這個:

c.execute('''UPDATE subreddits 
      SET average_score = ? WHERE ? = subreddit_id;''', (index[0],index[1])) 
+0

非常感謝!這樣一個愚蠢的事情被抓住 – kopo222

+0

你非常歡迎。快樂的編碼給你:-) – bernie