python - psycopg2没有错误但未插入数据库

标签 python python-3.x psycopg2

我正在使用下面的类,并且可以使用“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")

最佳答案

您是否在插入后执行 conn.commit() 来提交事务?此外,您有时还需要 cur.close() conn.close() 来彻底关闭。

您还可以使用自动提交模式。正如 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)

关于python - psycopg2没有错误但未插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48892145/

相关文章:

python - 当我的计算机上有 Python 2、Python 3 和 Anaconda 时,如何控制将包 pip 安装到哪个 Python 发行版?

django - 图像未在 Django 中上传

python-3.x - 使用 python 的模块 psycopg2 打印 SQL 执行计划

python - 如何从 pandas DataFrame 中获取 "unpivot"特定列?

python - 平均后图像全灰

python - scipy curve_fit 在简单的线性拟合上失败了吗?

python-3.x - 突出显示python中的文本并将其保存在word文件中

python - 索引错误: tuple index out of range with psycopg2

python - 带有 gevent 的 SQLAlchemy + PostgreSQL 的驱动程序是什么?

Python:从一月到当月动态选择列