eolas/neuron/233bf7c7-59e9-471c-8275-895571468b75/Using_SQLite_with_Python.md
2024-11-13 18:22:06 +00:00

1.6 KiB

tags created
python
databases
SQL
SQLite
Thursday, November 07, 2024

Using SQLite with Python

SQLite is part of the core library, you do not require a separate package

import sqlite3

Connect to database

Connect to an existing SQLite .db file or create a new database with the same command:

connection = sqlite3.connect("my_database.db")

Disconnect from database

connection.close()

Querying

connect exposes a cursor entity. This is used for executing changes against the database file.

Example: creating a table

CREATE_TAGS_TABLE = """
CREATE TABLE IF NOT EXISTS tags (
    name TEXT PRIMARY KEY
)
"""

cursor = connection.cursor()
cursor.execute(CREATE_TAGS_TABLE)
cursor.commit()

# Confirm changes

cursor.execute("SELECT name from sqlite_master WHERE type='table'")
print(cursor.fetchall())
# (tags)

Prepared statements and parameterised queries

Parameterised queries

username = "thomas"
password = "123"
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?",
            (username, password))

Alternatively, pass the tuple directly:

login_data = ("thomas", "123")
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?",
               login_data)

Prepared statements

With prepared statements you have to pass in the parameters

user_data = {
    "username": "thomas",
    "email": "thomas@email.com"
}

cursor.execute("INSERT INTO users (username, email) VALUES (:username, :email)")