【问题标题】:Update query on PostgreSQL table not workingPostgreSQL 表上的更新查询不起作用
【发布时间】:2023-04-08 10:23:01
【问题描述】:

我正在尝试使用 Python 代码构建一个 PostgreSQL 数据库来模拟锦标赛。玩家表包含四列 - 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)

我知道我不应该将获胜和匹配设置为 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() 中的更新查询,这似乎不起作用。我尝试在testReportMatches() 中两次调用reportMatch() 之前和之后打印排名,但他们的比赛和胜利都是0。不知何故,数据库中的比赛和胜利没有更新。

【问题讨论】:

    标签: python database postgresql


    【解决方案1】:

    您需要在reportMatch 函数的末尾使用conn.commit() 提交事务。

    psycopg2 usage

    【讨论】:

    • 谢谢。我不敢相信我是个白痴,我忽略了提交。
    猜你喜欢
    • 2015-01-19
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多