2016-04-03 24 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 
相关问题