技能标识:database-query-best-practices
Prevent connection pool exhaustion when querying Railway PostgreSQL database. Use when (1) Running database queries from local environment, (2) Diagnosing "too many clients" errors, (3) Writing Python scripts that query production DB, (4) Checking connection pool status. CRITICAL - Always close connections immediately after use, use context managers, check pool status before queries.
关键技能 - 在查询RAILWAY数据库前请先阅读此内容
从本地开发环境查询Railway生产数据库时,可能会遇到:
psycopg2.OperationalError: sorry, too many clients already
这种情况发生在:
在执行任何数据库查询前,检查活跃连接数:
bash
python3 << EOF
import psycopg2
DATABASE_URL = postgresql://postgres:password@host:port/railway
try:
conn = psycopg2.connect(DATABASEURL, connecttimeout=10)
cur = conn.cursor()
# 检查活跃连接数
cur.execute(
SELECT count(*)
FROM pgstatactivity
WHERE datname = railway
)
active = cur.fetchone()[0]
# 检查连接池限制
cur.execute(SHOW max_connections)
max_conn = cur.fetchone()[0]
print(f活跃连接数: {active}/{max_conn})
if active > int(max_conn) * 0.9:
print(f警告: 连接池使用率已达 {(active/int(max_conn))*100:.1f}%)
print(建议在查询前关闭开发服务器)
else:
print(连接池状态良好 - 可安全查询)
cur.close()
conn.close()
except Exception as e:
print(f无法连接: {e})
print(\n解决方案:)
print(1. 终止本地开发服务器: pkill -9 -f npm run dev)
print(2. 等待30秒让连接关闭)
print(3. 重试)
EOF
切勿这样做:
python
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute(SELECT * FROM users)
始终这样做:
python
import psycopg2
DATABASE_URL = postgresql://...
try:
conn = psycopg2.connect(DATABASEURL, connecttimeout=30)
cur = conn.cursor()
# 执行查询
cur.execute(SELECT * FROM users)
results = cur.fetchall()
# 处理结果...
finally:
# 始终在finally块中关闭
if cur:
cur.close()
if conn:
conn.close()
对于一次性查询,打开连接、查询、立即关闭:
python
def getusercount():
获取用户数量 - 连接在函数内打开和关闭
conn = None
try:
conn = psycopg2.connect(DATABASEURL, connecttimeout=30)
cur = conn.cursor()
cur.execute(SELECT COUNT(*) FROM users)
count = cur.fetchone()[0]
cur.close()
return count
finally:
if conn:
conn.close() # 连接立即释放
如果需要运行数据库查询,先停止开发服务器:
bash
尽可能使用Railway CLI代替Python脚本:
bash
这使用Railway管理的连接,不会消耗本地连接池。
如果遇到too many clients already:
bash
railway run psql -c
SELECT
pid,
usename,
application_name,
client_addr,
state,
query_start
FROM pgstatactivity
WHERE datname = railway
ORDER BY query_start DESC
LIMIT 20
bash
railway run psql -c
SELECT pgterminatebackend(pid)
FROM pgstatactivity
WHERE datname = railway
AND state = idle
AND query_start < NOW() - INTERVAL 10 minutes
在执行任何数据库查询前,请确认:
黄金法则:
使用后立即关闭数据库连接。
查询期间切勿在开发服务器中保持连接打开。
最佳实践:
更佳方案:
使用Railway CLI进行临时查询,而不是Python脚本。
以下为平台配置的接入选项,并非逐项实测通过。能否安装取决于客户端支持、技能来源和运行环境:
帮我安装 SkillHub 和 database-query-best-practices-1776058981 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 database-query-best-practices-1776058981 技能
skillhub install database-query-best-practices-1776058981
文件大小: 2.91 KB | 发布时间: 2026-4-14 11:19