CodingNic

Databases and Persistence

Inserting Data

Databases and Persistence 15 min read

Inserting Data

Inserting Data

Now that you have a table, it’s time to store real data in it.

This is where your database becomes useful.

What You Will Do

You will:

  • Insert a user into the database
  • Save the data
  • Confirm it was added

Step 1: Update database.py

Replace your code with this:

python
import sqlite3

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

# insert data
cursor.execute("INSERT INTO users (name) VALUES (?)", ("John",))

conn.commit()
conn.close()

print("User inserted successfully")

Step 2: Run the File

bash
python database.py

What Just Happened?

  • A new row was added to the users table
  • The name “John” was stored
  • The database now contains data

Important Concept

Why Use ?

python
cursor.execute("INSERT INTO users (name) VALUES (?)", ("John",))
  • The ? is a placeholder
  • It safely inserts data into the query
  • Prevents errors and security issues

Step 3: Insert Multiple Users

Try adding more:

python
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Bob",))

Run the file again.

Now your database has multiple users.

Why This Matters

You are now:

  • Storing real data
  • Building persistent applications
  • Moving from temporary → permanent data

Common Mistakes

  • ❌ Forgetting conn.commit() (data won’t save)
  • ❌ Missing comma in tuple → (“John”,)
  • ❌ Typing "John" instead of ("John",)

Summary

  • You inserted data into a table
  • You stored real user information
  • Your app can now remember data

In the next lesson, you’ll learn how to retrieve this data.