gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:03:09 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com