如何使用 psycopg3 连接到远程数据库

Alo*_*rad 2 python postgresql psycopg2 psycopg3

我正在使用 Psycopg3(不是 2!),但我不知道如何连接到远程 Postgres 服务器

psycopg.connect(connection_string)
Run Code Online (Sandbox Code Playgroud)

https://www.psycopg.org/psycopg3/docs/

谢谢!

小智 6

Psycopg3 使用 postgresql连接字符串,它可以是关键字=值元素的字符串(用空格分隔)

with psycopg.connect("host=your_server_hostname port=5432 dbname=your_db_name") as conn:
Run Code Online (Sandbox Code Playgroud)

或一个 URI

with psycopg.connect("postgresql://user:user_password@db_server_hostname:5432") as conn:
Run Code Online (Sandbox Code Playgroud)

因此,将所有内容与他们文档中的示例(与上面连接字符串中的一个示例混合)放在一起:

# Note: the module name is psycopg, not psycopg3
import psycopg

# Connect to an existing database
with psycopg.connect("postgresql://user:user_password@db_server_hostname:5432") as conn:

    # Open a cursor to perform database operations
    with conn.cursor() as cur:

        # Execute a command: this creates a new table
        cur.execute("""
            CREATE TABLE test (
                id serial PRIMARY KEY,
                num integer,
                data text)
            """)

        # Pass data to fill a query placeholders and let Psycopg perform
        # the correct conversion (no SQL injections!)
        cur.execute(
            "INSERT INTO test (num, data) VALUES (%s, %s)",
            (100, "abc'def"))

        # Query the database and obtain data as Python objects.
        cur.execute("SELECT * FROM test")
        cur.fetchone()
        # will return (1, 100, "abc'def")

        # You can use `cur.fetchmany()`, `cur.fetchall()` to return a list
        # of several records, or even iterate on the cursor
        for record in cur:
            print(record)

        # Make the changes to the database persistent
        conn.commit()
Run Code Online (Sandbox Code Playgroud)