Python · Advanced level

Advanced level · Module 3: Python and SQL Databases · Lesson 2 of 4

Using sqlite3 from Python Safely

Connect to a database from Python and run parameterised queries that are safe from SQL injection.

In this lesson you will

  • Execute queries and fetch results
  • Always use parameter placeholders

Key concepts

connection/cursorparameterised querySQL injectionrow_factory

The lesson

Python's sqlite3 module connects to a database file and runs SQL. Use a cursor to execute statements and fetch results.

Never build SQL by joining strings with user input; a value like ' OR 1=1 -- could change the meaning of the query (SQL injection). Always use parameters: cur.execute('SELECT * FROM products WHERE name = ?', (name,)).

Put database code in its own module of small functions — add_product, record_sale, daily_report — so the rest of the program never writes SQL directly.

Step by step

  1. Connect to shop.db with sqlite3.
  2. Write add_product() using a parameterised INSERT.
  3. Write daily_report() that returns rows from a SELECT.
  4. Try an injection string against an unsafe query on a test database, then show the parameterised version is safe.

Practice activity

Write a data-access module with functions add_product, record_sale and daily_report using parameterised queries.

Expected result: A data-access module that passes tests and resists the injection demonstration.

Check your understanding

  1. How do parameter placeholders prevent SQL injection?

    Show answer

    Values are sent separately from the SQL text, so input is never executed as SQL.

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.