ページの先頭行へ戻る
Enterprise Postgres 17 SP1 アプリケーション開発ガイド

8.4 アプリケーション開発

PEP 249 - Python Database API Specification v2.0に準拠したインタフェースで開発を行うことが可能です。詳細はOSSのPsycopgのドキュメント(https://www.psycopg.org/psycopg3/docs/)を参照してください。

以下はPython言語用パッケージ(psycopg)を使ったアプリケーションの例です。

import psycopg

# Connect to an existing database
with psycopg.connect("host=localhost port=27500 dbname=test user=postgres") 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 IF NOT EXISTS 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")

        # 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()

ただし、Python言語用パッケージ(psycopg)を使用する場合、以下の点がOSSのPsycopgと異なります。