admin管理员组

文章数量:1309939

I am studying the psycopg3 library for working with postgresql, I wanted to know if I applied the correct approach to working with psycopg3. I recently learned what pool connections are, so I wrote the following code:

from flask import Flask
from psycopg_pool import ConnectionPool

app = Flask(__name__)
pool = ConnectionPool(conninfo='dbname=test user=test password=test',min_size=4, max_size=10)

@app.route("/")
def index():
    with pool.connection() as conn:
        ans = conn.execute("SELECT * FROM users;").fetchall()
        return {"result": ans}

Before this I just created a connection using the old approach but I didn't know about the pool:

from flask import Flask
import psycopg2

app = Flask(__name__)

def db_connect():
    conn = psycopg2.connect(database="test", user="test",
        password="test.", host="localhost", port=5432)
    return conn

@app.route("/")
def index():
    with db_connect() as conn:
        with conn.cursor() as cur:
            cur.execute("SELECT * FROM users;")
            ans = cur.fetchall()
            return {"result": ans}

I would like to know if I am using and programming psycopg3 correctly.

本文标签: pythonCorrect use of psycopg3Stack Overflow