liveBook · Manning

Database connection

As explained in Python Concurrency with asyncio

A database connection is an active communication channel or session through which software sends operations to and receives results from a database system.

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

How Python Concurrency with asyncio covers it

How deep it goes
Explains connection setup, version verification, closure, parameterized inserts, and a concurrent-use failure.
Examples
Uses an e-commerce product database, server-version output, and randomized brand, product, and SKU inserts.
What it assumes
Assumes a running local Postgres instance and basic Python asynchronous programming; introduces connection setup from the beginning.
What you can do after
Operate/configure an asyncpg connection, execute parameterized database operations, verify access, and close the connection.
How it connects
Ties database connections to Postgres, asyncpg, asynchronous programming, SQL queries, parameterized SQL, and coroutines.

Also explained in

Compare how 6 books explain database connection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.