How do I read and write SQLite databases with sqlite3?

SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine. The sqlite3 module in Python allows for easy interaction with SQLite databases. Below is a simple example illustrating how to read from and write to an SQLite database with the sqlite3 module.

import sqlite3 # Connect to an SQLite database (or create it if it doesn't exist) connection = sqlite3.connect("example.db") # Create a cursor object using the cursor() method cursor = connection.cursor() # Create a table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL ) ''') # Insert a record into the table cursor.execute(''' INSERT INTO users (name, age) VALUES (?, ?) ''', ('John Doe', 30)) # Commit the changes connection.commit() # Read records from the table cursor.execute('SELECT * FROM users') # Fetch all results rows = cursor.fetchall() for row in rows: print(row) # Close the connection connection.close()

SQLite Python sqlite3 database CRUD operations