TIL: Running SQLite Queries from Python Command Line

Read as Markdown

Sqlite command output

Python provides a simple interface to run SQLite queries from the command line. The syntax is straightforward: python3 -m sqlite3 database query Here’s an example using a GitHub database with the table repos and a query to return five rows:

$python3 -m sqlite3 ../../Downloads/github.db "select name, html_url from repos limit 5"
('dotfiles', 'https://github.com/marksteve/dotfiles')
('djangopackages', 'https://github.com/djangopackages/djangopackages')
('honzajavorek.cz', 'https://github.com/honzajavorek/honzajavorek.cz')
('dashboard', 'https://github.com/openelections/dashboard')
('dotFiles', 'https://github.com/harish2704/dotFiles')

Command Line Options

python3 -m sqlite3 --help
usage: python -m sqlite3 [-h] [-v] [filename] [sql]

Python sqlite3 CLI

positional arguments:
  filename       SQLite database to open (defaults to ':memory:'). A new database is created if the file does not previously exist.
  sql            An SQL query to execute. Any returned rows are printed to stdout.

options:
  -h, --help     show this help message and exit
  -v, --version  Print underlying SQLite library version

You can view the implementation in the CPython Source Code