【问题标题】:How to specify Schema in psycopg2 connection method?如何在 psycopg2 连接方法中指定 Schema?
【发布时间】:2019-12-12 06:02:14
【问题描述】:

使用 psycopg2 模块通过 python 连接到 PostgreSQL 数据库。我可以使用以下连接方法执行所有查询。现在我想指定一个不同于 public 的模式来执行我的 SQL 语句。有什么办法可以在连接方法中指定schema名称吗?

conn = psycopg2.connect(host="localhost",
                            port="5432",
                            user="postgres",
                            password="password",
                            database="database",
                            )

我尝试直接在方法内指定架构。 schema="schema2" 但我收到以下编程错误。

ProgrammingError: invalid dsn: invalid connection option "schema"

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    当我们在psycopg2 中处理ThreadConnectionPool 并创建连接池时,我们就是这样做的。

    from psycopg2.pool import ThreadedConnectionPool
    
    db_conn = ThreadedConnectionPool(
        minconn=1, maxconn=5,
        user="postgres", password="password", database="dbname", host="localhost", port=5432,
        options="-c search_path=dbo,public"
    )
    

    您在 params 中看到 options 键。我们就是这样做的。

    当您使用来自该连接的游标执行查询时,它将按从左到右的顺序搜索options 中提到的那些架构,即dbo,public

    你可以试试这样的:

    psycopg2.connect(host="localhost", 
                     port="5432", 
                     user="postgres", 
                     password="password", 
                     database="database", 
                     options="-c search_path=dbo,public")
    

    希望这对你有帮助。

    【讨论】:

      【解决方案2】:

      如果您使用的是字符串形式,您需要对 options 参数进行 URL 转义:

      postgresql://localhost/airflow?options=-csearch_path%3Ddbo,public
      

      (%3D = = 的 URL 编码)

      例如,如果您使用 SQLAlchemy,这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2021-11-22
        • 2015-04-17
        • 2020-04-06
        • 1970-01-01
        • 2019-06-17
        • 2011-07-26
        • 2021-07-26
        • 2011-10-19
        • 2020-08-01
        相关资源
        最近更新 更多