intermediate#python#sqlite#databases
Working with Databases in Python using SQLite
Learn how to use the SQLite database in Python to store and retrieve data, including creating tables, inserting data, and querying data.
Introduction to SQLite
SQLite is a lightweight disk-based database library that doesn’t require a separate server process.
Connecting to the Database
You can connect to the database using the following command:
import sqlite3
# connect to the database
conn = sqlite3.connect('example.db')
# create a cursor object
cursor = conn.cursor()
Creating Tables
You can create tables in the database using the CREATE TABLE statement.
# create a table
cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
Inserting Data
You can insert data into the tables using the INSERT INTO statement.
# insert data
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('John Doe', 30))
# commit the changes
conn.commit()