我使用 psycopg2 在 Python 上连接到 PostgreSQL,我想使用连接池。
当我执行 INSERT 查询时,我不知道我应该做什么而不是 commit() 和 rollback()。
db = pool.SimpleConnectionPool(1, 10,host=conf_hostname,database=conf_dbname,user=conf_dbuser,password=conf_dbpass,port=conf_dbport)
# Get Cursor
@contextmanager
def get_cursor():
con = db.getconn()
try:
yield con.cursor()
finally:
db.putconn(con)
with get_cursor() as cursor:
cursor.execute("INSERT INTO table (fields) VALUES (values) RETURNING id")
id = cursor.fetchone()
如果没有 commit(),我无法获得插入记录的 ID。
最佳答案
更新 我无法测试代码,但我给你一些想法: 您在连接中而不是在数据库中进行提交
# Get Cursor
@contextmanager
def get_cursor():
con = db.getconn()
try:
yield con
finally:
db.putconn(con)
with get_cursor() as cursor:
con.cursor.execute("INSERT INTO table (fields) VALUES (values) RETURNING id")
con.commit()
id = cursor.fetchone()
或
# Get Cursor
@contextmanager
def get_cursor():
con = db.getconn()
try:
yield con.cursor()
con.commit()
finally:
db.putconn(con)
with get_cursor() as cursor:
con.cursor.execute("INSERT INTO table (fields) VALUES (values) RETURNING id")
id = cursor.fetchone()
存在连接池是因为创建到数据库的新连接可能很昂贵并且不能避免提交或回滚。因此您可以毫无问题地提交数据,提交数据不会破坏连接。
关于python - 如何在 psycopg2 连接池中使用 "INSERT"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29621532/