It's a familiar story. Your friends all brag about their humongous databases. They go on and on about MySQL this and Redis that, and "oh can you believe they swapped out Mongo for Snowflake!?!" and they all laugh and you pretend to laugh along. But inside you're sad because you don't have a database. Well today is your lucky day. Today you get a database of your very own.

One of the sleekest and slickest databases out there is SQLite. It's so lean that it got folded right into standard Python as the sqlite3 library. It's the single most used database in the world, and its code is entirely open source, in the public domain.

If you're already working in Python, you have SQLite installed.

import sqlite3

Create a new database and give it a filename.
Open it up and get a cursor, a way to run commands and get results.

connection = sqlite3.connect("my_first.db")
cursor = connection.cursor()

Create a new table within the database.
Name each column and declare the type of data it will hold.

cursor.execute("CREATE TABLE breakfast (day_of_week TEXT, food TEXT)")

Add a couple of rows to the table.

cursor.execute("INSERT INTO breakfast VALUES ('Monday', 'cereal')")
cursor.execute("INSERT INTO breakfast VALUES ('Wednesday', 'eggs')")

Read those rows back out.

cursor.execute("SELECT * FROM breakfast")

Show off the results.

print(cursor.fetchall())

Wrap up the database session.

connection.close()

Congratulations! You have a database of your own to use for whatever you want! Now you can feel sad about other things.


(For copy/pasting convenience)

import sqlite3
connection = sqlite3.connect("my_first.db")
cursor = connection.cursor()
cursor.execute("CREATE TABLE breakfast (day_of_week TEXT, food TEXT)")
cursor.execute("INSERT INTO breakfast VALUES ('Monday', 'cereal')")
cursor.execute("INSERT INTO breakfast VALUES ('Wednesday', 'eggs')")
cursor.execute("SELECT * FROM breakfast")
print(cursor.fetchall())
connection.close()