A database connection is the active interface software uses to exchange commands and data with a database service. With asyncpg, an application connects to Postgres, runs queries through the connection, reads results, and closes it when finished. section 5.2
Connecting to a product database
An e-commerce application connects to a local Postgres database, retrieves the server version to confirm connectivity, and then closes the connection. The same connection can execute parameterized inserts for brands, products, and SKUs. section 5.2 section 5.5.1
Listing 5.1 Connecting to a Postgres database as the default user
import asyncpg
import asyncio
async def main():
connection = await asyncpg.connect(host='127.0.0.1',
port=5432,
user='postgres',
database='postgres',
password='password')
version = connection.get_server_version()
print(f'Connected! Postgres version is {version}')
await connection.close()
asyncio.run(main())
Shows the complete asyncpg connection flow, including connection parameters, server-version retrieval, and explicit cleanup. section 5.2
Use a connection deliberately:
- Pass connection details such as host, port, user, database, and password to asyncpg.connect. section 5.2
- Do not share one connection across coroutines waiting for incoming data; concurrent use can raise a RuntimeError. section 5.5.1





