2011-01-19 60 views
3

編輯:經過一些測試後,我發現它不是失敗的加點方法。Sqlite更新不工作正確 - python

我正在爲一個irc bot做一個小遊戲。這種方法會更新數據庫中的分數'分數',只有兩名玩家。這是一個sqlite數據庫。這主要是更新SQL不正確。

感謝

def addpointo(phenny, id, msg, dude): 
try: 
    for row in c.execute("select score from score where id = '0'"): 
    for bow in c.execute("select score from score where id = '1'"): 
    if int(row[0]) == 3: 
    phenny.say("Winner is " + dude) 
    clear("score") # clear db 
    clear("sap") # clear db 
    elif int(bow[0]) == 3: 
    phenny.say("Winner is " + dude) 
    clear("score") # clear db 
    clear("sap") # clear db 
    else: 
    phenny.say(msg) 
    s = c.execute("select score from score where id=?", id) 
    a = int(s.fetchone()[0]) + 1 
    print a 
    c.execute("update score SET score =? where id =?", (a, id)) #here i got some prolem 
    conn.commit() 
except Exception: 
    phenny.say("Error in score. Try to run '.sap clear-score' and/or '.sap clear-sap'") 
    pass 

,這是我創造的得分分貝

def createscore(): 
if not (checkdb("score") is True): 
    c.execute('''create table score (id int, score int)''') 
    c.execute('insert into score values (0, 0)') 
    conn.commit() 
    c.execute('insert into score values (1, 0)') 
    conn.commit() 

錯誤信息的方式:參數是不支持的類型

+0

你是什麼意思是「不工作的權利」嗎?你遇到了什麼錯誤? – CanSpice 2011-01-19 21:58:31

+1

你有沒有看過sqlite模塊?另外,你應該閱讀使用SQL。你的設計很明顯缺乏對使用數據庫的理解。 – Falmarri 2011-01-19 22:00:10

+0

我只得到這個錯誤:參數是不受支持的類型 – Enumto 2011-01-19 22:06:11

回答

2

的。在你的最後一個選擇

錯誤

This

s = c.execute("select score from score where id='id'") 

必須寫成

s = c.execute("select score from score where id=?", id) 
2

您有其他嚴重的問題與您的代碼假定「C」是一個光標。 SQLite遊標一次獲取下一個結果行(即每次通過for循環)而不是所有的事先。如果您重新使用遊標,則會用新的遊標替換當前查詢。例如這個代碼將只運行循環一次:

for row in c.execute("select * from score"): 
    for dummy in c.execute("select 3"): 
     print row, dummy 

您的解決方案包括:

  • 在末尾添加.fetchall():c.execute( 「SELECT * FROM分數」) .fetchall()將所有行放在前面,而不是一次一個。

  • 使用不同的遊標所以通過每一個迭代不影響他人

  • 創建一個新的光標 - 取代c.execute(「...」)與conn.cursor()執行( 「...」) 最近的pysqlite版本讓你可以做conn.execute(「...」),它可以在幕後進行。

光標是非常便宜,所以不要試圖去保護他們 - 用你想要儘可能多的 - 你不會有這樣的錯誤。

一般來說,在同一系列的循環中重複使用迭代器並修改你正在迭代的內容是非常小心的。各種類別的行爲方式各不相同,所以最好假設他們不喜歡它,除非另有說明。

26

儘管原作者最有可能繼續前進,但我想我會在這裏爲未來的Google員工留下一個答案(如我^ _ ^)。

我覺得這裏發生了什麼是以下錯誤......

ValueError: parameters are of unsupported type

...實際上是從以下行來(出乎筆者說的話)。

s = c.execute("select score from score where id=?", id) 

的這裏的問題是Cursor.execute接受查詢字符串作爲第一個參數(他有哪些右),listtuple,或者dict作爲第二個參數。在這種情況下,他需要換一個元組或列表id,像這樣:

s = c.execute("select score from score where id=?", (id,)) 

列表或元組可與位置參數來使用(這是當你使用一個問號?的佔位符) 。您還可以使用名爲參數的dict:key,具體如下:

s = c.execute("select score from score where id=:id", {"id": id})