使用 psycopg2 连接到 psql docker 容器但无法读取或写入
connected to psql docker container with psycopg2 but unable to read or write
我正在尝试 运行 在 docker 容器中创建一个 postgres 数据库,运行使用一个 class 来调用一个小的 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()
结果:
"""
追溯(最近一次通话):
文件“/Users/myname/projects/myproject/dataGathering/postgres.py”,第 21 行,位于
db.query("插入测试 (id) 值('test2')")
查询中的文件“/Users/myname/projects/myproject/dataGathering/postgres.py”,第 11 行
self.cur.execute(查询)
psycopg2.errors.UniqueViolation:重复键值违反了唯一约束“id_pkey”
详细信息:键 (id)=(test) 已经存在。
"""
在没有冲突 ID 的情况下插入内容不会引发错误,但也不会在数据库中给出任何结果。 SELECT查询同信
你没有做:
conn.commit()
因此您的更改未提交。
从这里开始:
https://www.psycopg.org/docs/connection.html
" 关闭()
现在关闭连接(而不是每次执行 del 时)。从此时起,连接将无法使用;如果尝试对连接进行任何操作,将引发 InterfaceError。这同样适用于所有尝试使用连接的游标对象。请注意,关闭连接而不首先提交更改将导致任何挂起的更改被丢弃,就像执行了 ROLLBACK 一样(除非选择了不同的隔离级别:请参阅 set_isolation_level())。"
我正在尝试 运行 在 docker 容器中创建一个 postgres 数据库,运行使用一个 class 来调用一个小的 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()
结果: """ 追溯(最近一次通话): 文件“/Users/myname/projects/myproject/dataGathering/postgres.py”,第 21 行,位于 db.query("插入测试 (id) 值('test2')") 查询中的文件“/Users/myname/projects/myproject/dataGathering/postgres.py”,第 11 行 self.cur.execute(查询) psycopg2.errors.UniqueViolation:重复键值违反了唯一约束“id_pkey” 详细信息:键 (id)=(test) 已经存在。 """
在没有冲突 ID 的情况下插入内容不会引发错误,但也不会在数据库中给出任何结果。 SELECT查询同信
你没有做:
conn.commit()
因此您的更改未提交。
从这里开始:
https://www.psycopg.org/docs/connection.html
" 关闭()
现在关闭连接(而不是每次执行 del 时)。从此时起,连接将无法使用;如果尝试对连接进行任何操作,将引发 InterfaceError。这同样适用于所有尝试使用连接的游标对象。请注意,关闭连接而不首先提交更改将导致任何挂起的更改被丢弃,就像执行了 ROLLBACK 一样(除非选择了不同的隔离级别:请参阅 set_isolation_level())。"