You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用psycopg2创建PostgreSQL表时遭遇invalid dsn错误求解决

解决psycopg2.ProgrammingError: invalid dsn: invalid connection option "dBname"错误

这个问题根源很明确——你写错了连接参数的大小写!psycopg2的DSN(数据源名称)里,指定数据库名的参数必须是全小写的dbname,而你写成了dBname(B大写),这就导致解析器识别不了这个参数,直接抛出了错误。

修正后的基础代码

先把连接字符串里的参数名改对,同时用try/finally确保连接最终会被关闭:

def create():
    # 修正dbname为全小写
    conn = psycopg2.connect("dbname='database1' user='postgres' password='postgres' host='localhost' port='5432'")
    try:
        cur = conn.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS store(item TEXT,quantity INTEGER,price REAL)")
        conn.commit()
    finally:
        # 无论是否出错,都保证连接关闭
        conn.close()

更优雅的写法(推荐)

用Python的with上下文管理器可以自动处理连接和游标的生命周期,还能在无异常时自动提交事务,代码更简洁安全:

def create():
    with psycopg2.connect("dbname='database1' user='postgres' password='postgres' host='localhost' port='5432'") as conn:
        with conn.cursor() as cur:
            cur.execute("CREATE TABLE IF NOT EXISTS store(item TEXT,quantity INTEGER,price REAL)")
    # 离开with块后,连接自动关闭,事务自动提交(无异常时)

额外优化:用关键字参数连接

你还可以放弃DSN字符串的方式,改用关键字参数建立连接,这样完全不用担心大小写问题,代码可读性也更高:

def create():
    with psycopg2.connect(
        dbname="database1",
        user="postgres",
        password="postgres",
        host="localhost",
        port="5432"
    ) as conn:
        with conn.cursor() as cur:
            cur.execute("CREATE TABLE IF NOT EXISTS store(item TEXT,quantity INTEGER,price REAL)")

这种写法不仅避开了DSN的格式陷阱,后续修改参数也更直观。

内容的提问来源于stack exchange,提问作者Lakshmi Ab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:22:38