Advanced Python: Databases (SQLite)

Goal

Step 1: Using SQLite


import sqlite3

# Connect to the database (creates daten.db if it doesn't exist)
conn = sqlite3.connect("daten.db")
cursor = conn.cursor()

# Create table if it does not exist
cursor.execute("CREATE TABLE IF NOT EXISTS user (name TEXT, age INTEGER)")

# Insert data
cursor.execute("INSERT INTO user VALUES ('Max', 20)")

# Save changes
conn.commit()

Explanation:

Step 2: Reading Data


# Read all data
cursor.execute("SELECT * FROM user")
data = cursor.fetchall()
print(data)

# Close connection
conn.close()

Explanation:

Practical Task