2016-04-03 45 views
0

你好,我有一個很難試圖使這一功能中,我必須:從數據庫中的記錄與Python和PostgreSQL返回一個元組列表

"""Returns a list of the players and their win records, sorted by wins. 

The first entry in the list should be the player in first place, or a player 
tied for first place if there is currently a tie. 

Returns: 
    A list of tuples, each of which contains (id, name, wins, matches): 
    id: the player's unique id (assigned by the database) 
    name: the player's full name (as registered) 
    wins: the number of matches the player has won 
    matches: the number of matches the player has played 
""" 

目前我有這個功能來嘗試解決:

def playerStandings(): 
    conn = connect() 
    c = conn.cursor() 
    c.execute("SELECT id, name \ 
      FROM players LEFT JOIN matches \ 
      ON players.id = matches.id_winner \ 
      ORDER BY players.id") 
    result = c.fetchall() 
    conn.close() 
    return result 

,當我運行代碼,我得到這個錯誤信息:在比賽

Traceback (most recent call last): File "tournament_test.py", line 152, in testStandingsBeforeMatches() File "tournament_test.py", line 61, in testStandingsBeforeMatches raise ValueError("Each playerStandings row should have four columns.") ValueError: Each playerStandings row should have four columns.

線152 _test.py是:

testStandingsBeforeMatches() 

和線61是:

if len(standings[0]) != 4: 
    raise ValueError("Each playerStandings row should have four columns.") 
[(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings 

最後變量 「排名」 是在管線54

standings = playerStandings() 

這對我的功能playerStandings()的呼叫是我的SQL腳本來創建數據庫和表格:

CREATE DATABASE tournament; 
\c tournament; 
CREATE TABLE players (id SERIAL, name TEXT, PRIMARY KEY (id)); 
CREATE TABLE matches (
    id_match SERIAL, 
    id_winner SERIAL REFERENCES players(id), 
    id_looser SERIAL REFERENCES players(id), 
    PRIMARY KEY (id_match) 
); 

我能做些什麼來解決這個問題?我真的很新的python所以我不明白它很好

+0

您是否使用與用於創建表的用戶相同的用戶連接到數據庫?你似乎遇到的是一個權限錯誤,連接你用來創建表的用戶會驗證它是否是。 – John

+0

嗨@John我編輯了正確的錯誤信息,請再次檢查 –

+0

該字典在每個元組中有4個項目,但查詢結果每行只有兩列,這就是代碼引發錯誤。 –

回答

0

我不使用postgresql,代碼可能不會在你的例程中直接使用,所以你需要在此基礎上修改讓它工作。我只是給你一些提示,讓你知道如何解決這個問題。

def playerStandings(): 
    conn = connect() 
    c = conn.cursor() 
    c.execute("SELECT id, name \ 
      FROM players LEFT JOIN matches \ 
      ON players.id = matches.id_winner \ 
      ORDER BY players.id") 
    result = c.fetchall()#get all id and name, I don't know the type of result, assume its a list of dicts. 

    for row in result: 
     #sql to get wins 
     c.execute("SELECT COUNT(*) AS wins FROM WHERE id_winner = row['id']"); 
     win_data = c.fetch() 
     row['wins'] = win_data['wins'] 
     #sql to get matches 
     c.execute("SELECT COUNT(*) AS matches FROM WHERE id_winner = row['id']" OR id_looser = row['id']) 
     match_data = c.fetch() 
     row['matches'] = match_data['matches'] 

    conn.close() 
    return result 
相關問題