psycopg2 没有错误但没有插入到数据库中

psycopg2 no error but not inserted into DB

我用的是下面的class,用"getAccount"的方法可以成功取到数据,但是"insertToken"的方法没有插入数据。我已经手动尝试了 SQL,它确实有效。我也没有收到任何错误。知道这里出了什么问题吗?

import psycopg2
import psycopg2.extras

class Database:
    variable = "blah"

    def getAccount(self):
        accountId = 0;
        username = ""
        password = ""
        try:
            conn = psycopg2.connect("dbname='token_generator' user='token_generator' host='myip' password='mypass'")
            cur = conn.cursor()
            try:
                cur.execute("""SELECT id, username, password from account where used = false limit 1""")
            except Exception as e: print(e)
            rows = cur.fetchall()
            for row in rows:
                accountId = row[0]
                username = row[1]
                password = row[2]
        except:
            print("I am unable to connect to the database")
        return (accountId, username, password)


    def insertToken(self, token, accountId):
        try:
            conn = psycopg2.connect("dbname='token_generator' user='token_generator' host='myip' password='mypass'")
            cur = conn.cursor()
            try:
                cur.execute("INSERT INTO token (token, account_id) VALUES (%s, %s)", (token, accountId))
            except Exception as e: print(e)
        except:
            print("I am unable to connect to the database")
SELECT * FROM token_generator.pg_stat_activity 

应该给你一个最近查询的列表。

如果您认为自己是 运行 的查询是手动工作的,那么您很可能不是 运行 您认为自己是 运行 的查询。这应该可以帮助您弄清楚您实际上是哪个查询 运行,然后进行相应的更改。

您是否在插入后 conn.commit() 提交事务?此外,您有时需要 cur.close() conn.close() 才能干净利落地关闭。

您也可以使用autocommit模式。正如 Jared 的评论所指出的那样,使用上下文管理器而不是 try/catch.

会更干净
with psycopg2.connect("dbname='token_generator' user='token_generator' host='myip' password='mypass'") as conn:
    conn.autocommit = True
    with conn.cursor() as cur:
        try:
            cur.execute("INSERT ...")
        except Exception as exc:
            print("Error executing SQL: %s"%exc)