我使用下面的课程,我可以使用" 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")
答案 0 :(得分:2)
在插入提交事务后你是在做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)
答案 1 :(得分:0)
SELECT * FROM token_generator.pg_stat_activity
应该为您提供最近查询的列表。
如果您认为自己运行的查询是手动运行的,那么您很可能无法运行您认为自己正在运行的查询。这可以帮助您确定您实际运行的查询,然后相应地进行更改。