~/Using SQLite in Python for a Todo App
May 14, 2023
To create a todo app with SQLite in Python, use the built-in sqlite3 module.
Set up the database:
1
2
3
4
5
6
|
import sqlite3
conn = sqlite3.connect("todo.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, task TEXT, done BOOLEAN)")
conn.commit()
|
Add a todo item:
1
2
3
|
def add_todo(task):
c.execute("INSERT INTO todos (task, done) VALUES (?, ?)", (task, False))
conn.commit()
|
Mark a task as done:
1
2
3
|
def mark_done(todo_id):
c.execute("UPDATE todos SET done = ? WHERE id = ?", (True, todo_id))
conn.commit()
|
List all todos:
1
2
3
|
def list_todos():
c.execute("SELECT id, task, done FROM todos")
return c.fetchall()
|
Read more in the Python sqlite3 documentation. Finish by closing the connection when done:
This covers basic create, update, and fetch operations for a todo application using SQLite in Python.