python - 如何在 psycopg2 连接池中使用 "INSERT"?

标签 python connection-pooling psycopg2 psycopg

我使用 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/

相关文章:

python - Psycopg2 Python SSL 支持未编译

python - 在 for 循环中调整 matplotlib 散点图大小

Python MySQLdb,完整插入查询执行,忽略错误插入

python - 如何使用来自多列的参数调用 pandas.rolling.apply?

.net - NHibernate 和 ADO.NET 连接池

python - 使用 python 创建 Postgres 数据库

python - 如何从 "Health"元素中提取文本

android - 如何在 Android Activity 之间共享 socket.io 连接?

java - 数据库中的总 session 数与 websphere 连接池中设置的不一样

postgresql - psycopg 错误,列不存在