Database Management · Intermediate level

Intermediate level · Module 5: Using Databases from Applications · Lesson 1 of 3

Connecting from Code

Connect to SQLite or PostgreSQL from a program, run queries and read results.

In this lesson you will

  • Open a database connection from code
  • Run queries and process results

Key concepts

database driverconnection stringcursor and resultsclosing connections

The lesson

Programs talk to databases through drivers: Python's built-in sqlite3 module for SQLite, or psycopg for PostgreSQL. You open a connection, run statements and read rows.

Keep connection details — host, database, user, password — in environment variables or a configuration file outside the code, never in source files that are shared.

Always close connections when finished, ideally with a with block (context manager), so connections are released even if an error occurs.

Step by step

  1. Connect to the NGO database from Python.
  2. Run a SELECT and print the rows.
  3. Move the connection details to environment variables.
  4. Use a with block to close the connection automatically.

Practice activity

Write a script that prints the distribution summary from the reporting view.

Expected result: The script prints the same results as the query tool and contains no passwords.

Check your understanding

  1. Where should database passwords be kept?

    Show answer

    In environment variables or configuration outside the source code.

  2. Why use a with block for connections?

    Show answer

    It closes the connection even if an error occurs.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.