Search code examples
pythonconnection-poolingpsycopg2psycopg

How to use "INSERT" in psycopg2 connection pooling?


I use psycopg2 to connect to PostgreSQL on Python and I want to use connection pooling.

I don't know what should I do instead commit() and rollback() when I execute INSERT query.

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()

I don't get id of inserted record without commit().


Solution

  • UPDATE I can not test the code but I give you some ideas: You do the commit in connection not in db

    # 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()
    

    or

    # 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()
    

    Connection pooling exist because creating a new connection to a db can be expensive and not to avoid commits or rollbacks. So you can commit your data without any issue, committing data will not destroy the connection.