为什么需要数据库连接池?如何配置?

中等

答题要点

# SQLAlchemy连接池
from sqlalchemy import create_engine

engine = create_engine(
    'postgresql://user:pass@localhost/db',
    pool_size=5,          # 常驻连接数
    max_overflow=10,      # 超出pool_size的最大连接数
    pool_timeout=30,      # 获取连接超时
    pool_recycle=1800,    # 连接回收时间(秒)
    pool_pre_ping=True,   # 使用前检查连接有效性
)

# 异步连接池(asyncpg)
import asyncpg

async def create_pool():
    pool = await asyncpg.create_pool(
        'postgresql://user:pass@localhost/db',
        min_size=5,
        max_size=20,
        max_inactive_connection_lifetime=300,
    )
    return pool

async def query_with_pool(pool):
    async with pool.acquire() as conn:
        result = await conn.fetch('SELECT * FROM users')
    return result

# psycopg2连接池
from psycopg2 import pool

connection_pool = pool.ThreadedConnectionPool(
    minconn=5,
    maxconn=20,
    host='localhost',
    database='db',
    user='user',
    password='pass'
)

conn = connection_pool.getconn()
try:
    with conn.cursor() as cur:
        cur.execute('SELECT * FROM users')
finally:
    connection_pool.putconn(conn)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题