Introduction to SQLite in Python

By xngo on June 5, 2019

The code below will show you how to create a table in SQLite. How to insert and fetch data from SQLite.

#!/usr/bin/python3
# Description: Using SQLite with Python.
 
# Import package.
import sqlite3
 
# Create a SQLite connection.
#   You can use ':memory:' instead of 'example.db' to create database in RAM.
conn = sqlite3.connect('example.db')
 
# Create a cursor.
cursor = conn.cursor()
 
# Execute SQL queries.
# #####################
# Create table
cursor.execute('''CREATE TABLE IF NOT EXISTS person
                    (name TEXT, age INTEGER, weight REAL)''')
 
# Insert data: It is much more secure to use parameter substitution(?).
people=[    ('John', 11, 142.4),
            ('Kim' , 37, 243.098),
            ('Joe' , 26, 163.8),
        ]
cursor.executemany("INSERT INTO person VALUES (?, ?, ?)", people)
 
# Save (commit) the changes.
# #####################
conn.commit()
 
# Fetch data from SQLite.
# #####################
for row in cursor.execute('SELECT * FROM person ORDER BY name'):
    name   = row[0]
    age    = row[1]
    weight = row[2]
    print(name, age, weight)
 
# Fetch 1 row.
values = ('John',)
cursor.execute('SELECT * FROM person WHERE name=?', values)
print(cursor.fetchone())

Output

Joe 26 163.8
John 11 142.4
Kim 37 243.098
('John', 11, 142.4)

Reference

  • https://docs.python.org/3.7/library/sqlite3.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.