已使用psycopg2连接到psql docker容器,但无法读取或写入

问题描述

我正在尝试在docker容器中运行一个postgres数据库,运行一个带有类的小型python程序来调用数据库

当我运行带有查询代码时,它似乎可以正常工作,但没有给出结果。 我可以看到我实际上访问了数据库,因为其中一个表具有id约束,当我尝试插入已经存在的东西时导致错误

使用TablePlus中的数据库工作正常。

代码

import psycopg2


class postgres():
    def __init__(self,db="foo",user="bar",password='baz',host='127.0.0.1',port=5432):
        self.conn = psycopg2.connect(
            database=db,user=user,password=password,host=host,port=port)
        self.cur = self.conn.cursor()

    def query(self,query):
        self.cur.execute(query)

        # self.cur.execute("CREATE TABLE test (id serial PRIMARY KEY,num integer,data varchar);")

    def close(self):
        self.cur.close()
        self.conn.close()


db = postgres()
db.query("INSERT INTO test (id) values('test2')")
db.close()

导致: “” 追溯(最近一次通话): 在第21行的“ /Users/myname/projects/myproject/dataGathering/postgres.py”文件中 db.query(“插入测试(id)值('test2')”) 查询中的文件“ /Users/myname/projects/myproject/dataGathering/postgres.py”,行11 self.cur.execute(查询) psycopg2.errors.UniqueViolation:重复的键值违反了唯一约束“ id_pkey” 详细信息:密钥(id)=(测试)已存在。 “”“

插入没有冲突ID的东西不会引起错误,但是在数据库中都不会产生任何结果。 SELECT查询具有相同的信念。

解决方法

您没有这样做:

conn.commit()

因此您的更改未提交。

从这里:

https://www.psycopg.org/docs/connection.html

“ close()

现在关闭连接(而不是每当执行del时)。从现在开始,该连接将无法使用;如果尝试对连接进行任何操作,都会引发InterfaceError。这同样适用于所有尝试使用该连接的游标对象。请注意,在没有先提交更改的情况下关闭连接将导致所有待处理的更改都被丢弃,就像执行了ROLLBACK一样(除非已选择其他隔离级别:请参见set_isolation_level())。“