我试图用python代码构建一个postgresql数据库来模拟锦标赛。players表包含四列-name、id、wins、matches。reportMatch()
函数接受两个参数,一个是特定匹配的赢家和输家的id,并更新数据库中的统计信息。它将使获胜者的“胜利”增加1,使双方的“比赛”增加1。
def reportMatch(winner, loser):
conn = connect()
c = conn.cursor()
SQL = 'update players set wins = 1 where id = %s;'
data = (winner, )
c.execute(SQL, data)
SQL = 'update players set matches = 1 where id = %s or id = %s;'
data = (winner, loser)
c.execute(SQL, data)
我知道我不应该将wins和matches设置为1,因为它不会递增当前值,但数据库当前没有匹配项。所以,我第一次运行它时,将值设置为1会暂时起作用。
上述函数通过客户端代码函数调用,
testReportMatches()
:def testReportMatches():
registerPlayer("Bruno Walton")
registerPlayer("Boots O'Neal")
registerPlayer("Cathy Burton")
registerPlayer("Diane Grant")
standings = playerStandings()
[id1, id2, id3, id4] = [row[1] for row in standings]
reportMatch(id1, id2)
reportMatch(id3, id4)
standings = playerStandings()
for (n, i, w, m) in standings:
if m != 1:
raise ValueError("Each player should have one match recorded.")
if i in (id1, id3) and w != 1:
raise ValueError("Each match winner should have one win recorded.")
elif i in (id2, id4) and w != 0:
raise ValueError("Each match loser should have zero wins recorded.")
print "7. After a match, players have updated standings."
registerPlayer()
用于将新播放器插入播放器数据库。playerStandings()
用于获取所有播放器的元组列表。我遇到的问题是
reportMatch()
中的更新查询,它似乎不起作用。我试着在两次呼叫reportMatch()
前和呼叫testReportMatches()
后打印出积分榜,但他们都有比赛,并且都以0获胜。不知何故,数据库中的匹配和获胜结果没有更新。 最佳答案
您需要在conn.commit()
函数的末尾提交reportMatch
事务。
见psycopg2 usage。