> Every page of the ganymede website is listed in https://eugo.io/docs/ganymede/llms.txt.

# PostgreSQL via Asyncpg

> PostgreSQL via Asyncpg: Work with data in PostgreSQL asynchronously. A Python demo notebook from ganymede.

Web page: https://eugo.io/docs/ganymede/demo_notebooks/data_storage/databases/postgres/asyncpg/
Notebook: https://eugo.io/docs/ganymede/demo_notebooks/data_storage/databases/postgres/asyncpg/asyncpg.ipynb (source: https://github.com/eugo-inc/ganymede/blob/main/demo_notebooks/data_storage/databases/postgres/asyncpg.ipynb)

Description:
- Work with data in PostgreSQL asynchronously

Resources:
- [GitHub] https://github.com/MagicStack/asyncpg
- [Docs] https://magicstack.github.io/asyncpg/current/index.html

Source and license:
- Some of these examples are adapted from the asyncpg README and documentation (https://github.com/MagicStack/asyncpg), Copyright (C) 2016-present the asyncpg authors and contributors, licensed under Apache-2.0. That code stays under its own license; see [THIRD_PARTY_NOTICES.md](https://github.com/eugo-inc/ganymede/blob/main/THIRD_PARTY_NOTICES.md).

## Environment variables

This notebook reads its settings from environment variables. Set them before starting Jupyter:

- `POSTGRES_HOST`: hostname of your PostgreSQL server
- `POSTGRES_USER`: PostgreSQL user name
- `POSTGRES_PASSWORD`: password for that user
- `POSTGRES_DB`: database to connect to (must exist)

## Example 1

Read data aysnchronously from an postgres database using `asyncpg`

```python
import asyncio
import asyncpg
import datetime
import os

async def run_test():
    conn = await asyncpg.connect(
        user=os.environ["POSTGRES_USER"],
        password=os.environ["POSTGRES_PASSWORD"],
        database=os.environ["POSTGRES_DB"],
        host=os.environ["POSTGRES_HOST"],
    )
    print("Connected to database")

    await conn.execute('''
        CREATE TABLE users(
            id serial PRIMARY KEY,
            name text,
            dob date
        )
    ''')

    # Insert a record into the created table.
    await conn.execute('''
        INSERT INTO users(name, dob) VALUES($1, $2)
    ''', 'Bob', datetime.date(1986, 12, 9))

    # Select a row from the table.
    row = await conn.fetchrow(
        'SELECT * FROM users WHERE name = $1', 'Bob')

    for r in row:
        print(r)

    await conn.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(run_test())
```
