CodingNic

Databases and Persistence

Creating Tables

Databases and Persistence 15 min read

Creating Tables

Creating Tables

Now that you have a database, you need a place to store data.

This is done using tables.

What is a Table?

A table is where your data is stored.

Think of it like a spreadsheet with columns and rows.

You will now create your first table.

What You Will Do

You will:

  • Create a table called users
  • Define columns for the data
  • Save the table in your database

Step 1: Open database.py

Update your file to this:

python
import sqlite3

conn = sqlite3.connect("database.db")
cursor = conn.cursor()

# create table
cursor.execute("""
CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT
)
""")

conn.commit()
conn.close()

print("Table created successfully")

Step 2: Run the File

bash
python database.py

What Just Happened?

  • A table named users was created

  • It has two columns:

    • id → unique number for each user
    • name → stores the user’s name

Important Concepts

PRIMARY KEY

  • Uniquely identifies each row
  • No two rows can have the same id

AUTOINCREMENT

  • Automatically increases the id
  • You don’t need to set it manually

Step 3: Avoid Duplicate Errors

If you run the script again, you may get an error:

table already exists

Fix this by updating your code:

python
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT
)
""")

Why This Matters

You now have:

  • A database file
  • A table to store data

Next, you will start adding real data.

Common Mistakes

  • ❌ Forgetting conn.commit()
  • ❌ Running without IF NOT EXISTS
  • ❌ Typos in SQL

Summary

  • Tables store your data
  • You created a users table
  • You defined columns

In the next lesson, you will insert data into your table.