我更新表的python代码是这样的: -
def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.
Args:
winner: the id number of the player who won
loser: the id number of the player who lost
"""
conn=connect()
cur=conn.cursor()
sql="UPDATE players SET wins = wins + 1 WHERE id = winner;"
cur.execute(sql)
sql="UPDATE players SET losses = losses + 1 WHERE id = loser;"
cur.execute(sql)
sql="INSERT INTO matches (player_a,player_b,result) VALUES (%s,%s,%s);"
data=(winner,loser,winner)
cur.execute(sql,data)
cur.close()
conn.close()
return
它正在做的是更新匹配表和玩家,如下所示: -
DROP TABLE IF EXISTS players CASCADE;
CREATE TABLE players(
id SERIAL PRIMARY KEY,
pl_name TEXT,
wins INTEGER DEFAULT 0,
losses INTEGER DEFAULT 0,
draws INTEGER DEFAULT 0,
matches INTEGER DEFAULT 0
);
DROP TABLE IF EXISTS matches CASCADE;
CREATE TABLE matches(
id SERIAL PRIMARY KEY,
pl_a INTEGER REFERENCES players(id),
pl_b INTEGER REFERENCES players(id),
result INTEGER DEFAULT NULL
);
现在,当我运行上述函数时,我得到的错误是: -
Traceback (most recent call last):
File "tournament_test.py", line 153, in <module>
testReportMatches()
File "tournament_test.py", line 84, in testReportMatches
reportMatch(id1, id2)
File "/vagrant/tournament/tournament.py", line 99, in reportMatch
cur.execute(sql)
psycopg2.ProgrammingError: column "winner" does not exist
LINE 1: UPDATE players SET wins = wins + 1 WHERE id = winner;
^
HINT: Perhaps you meant to reference the column "players.wins".
我被困在这一点上,我不知道如何比较&#39; id&#39;使用&#39; id&#39;我在变量&#39;获胜者&#39;
中收到的我只想更新id与获胜者ID匹配的行。我是新手,对于这些蹩脚的问题感到遗憾,但我正在加快学习的步伐。请帮助,谢谢。
答案 0 :(得分:1)
要在SQL查询中使用python变量,可以使查询的相关部分成为%s
的参数:
sql = "UPDATE players SET wins = wins + 1 WHERE id = %s;"
执行它时,将参数作为元组参数传递给execute方法:
cur.execute(sql, (winner,))