0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Asyncio 互換の PostgreSQLドライバ asyncpg

Last updated at Posted at 2022-09-06

Pythonプログラムに速度を求めていろいろasyncioを試しています。
(関連過去記事)
Python Asyncio入門 - Qiita
Python Asyncio で作る Socket Server -Qiita

Asyncio 互換の PostgreSQLドライバ asyncpg を試してみました。 特徴は速いことです。公式サイトで公開されている以下のパフォーマンスレポートをご参照ください。
PostgreSQL Driver Performance Benchmark Report

以下にasyncpgの簡単なサンプルプログラムを掲載します。

main.py
import asyncpg
import asyncio

GORILLA_CREATE_TABLE = \
    """
    CREATE TABLE IF NOT EXISTS gorilla(
        gollira_id SERIAL PRIMARY KEY,
        name TEXT NOT NULL,
        pos TEXT NOT NULL,
        age INT NOT NULL
    );"""
GORILLA_INSERT_TABLE = \
    """
    INSERT INTO gorilla (name, pos, age) VALUES ($1, $2, $3)
    """
GORILLA_DROP_TABLE = \
    """
    DROP TABLE IF EXISTS gorilla
    """
GORILLA_QUERY_TABLE = \
    """
    SELECT * FROM gorilla
    """

async def main():
    connection = await asyncpg.connect(host='127.0.0.1',
                                       port=5433,
                                       user='postgres',
                                       database='gorillas',
                                       password='xxxxxxxxxx')
    
    status = await connection.execute(GORILLA_DROP_TABLE)
    print(status)
    status = await connection.execute(GORILLA_CREATE_TABLE)
    print(status)
    await connection.executemany(GORILLA_INSERT_TABLE, 
            [('モモタロウ','父ゴリラ',24), ('ゲンキ','母ゴリラ', 35),
             ('ゲンタロウ','長男ゴリラ', 9), ('キンタロウ','子ゴリラ', 4)])
    golilla_list = await connection.fetch(GORILLA_QUERY_TABLE)
    for golli in golilla_list:
        print(f'ゴリラid: {golli["gollira_id"]}, 名前: {golli["name"]},'\
              f'地位: {golli["pos"]}, 年齢: {golli["age"]}')
 
    await connection.close()

asyncio.run(main())

実行結果です。

python main.py
DROP TABLE
CREATE TABLE
ゴリラid: 1, 名前: モモタロウ,地位: 父ゴリラ, 年齢: 24
ゴリラid: 2, 名前: ゲンキ,地位: 母ゴリラ, 年齢: 35
ゴリラid: 3, 名前: ゲンタロウ,地位: 長男ゴリラ, 年齢: 9
ゴリラid: 4, 名前: キンタロウ,地位: 子ゴリラ, 年齢: 4

今回は以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?