pysqlite3

0.6.0 · active · verified Wed Apr 15

pysqlite3 is a Python library that provides a DB-API 2.0 compliant interface for SQLite 3.x databases. It effectively takes the `sqlite3` module from the Python standard library and packages it separately, often with a more recent, statically compiled SQLite library that includes additional features not always present in system-bundled SQLite versions. The current version is 0.6.0. It offers a self-contained binary distribution (`pysqlite3-binary`) that requires no external dependencies.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an SQLite database (in-memory in this case) using `pysqlite3`, create a table, insert data with parameter substitution to prevent SQL injection, and query the data. It also includes basic error handling for insertions.

import pysqlite3

# Connect to an in-memory database
conn = pysqlite3.connect(':memory:')
cursor = conn.cursor()

# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL
)
''')
conn.commit()

# Insert data
try:
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Alice', 'alice@example.com'))
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Bob', 'bob@example.com'))
    conn.commit()
    print('Data inserted successfully.')
except pysqlite3.IntegrityError as e:
    print(f'Error inserting data: {e}')
    conn.rollback()

# Query data
cursor.execute("SELECT id, name, email FROM users")
rows = cursor.fetchall()

print('\nUsers:')
for row in rows:
    print(f'ID: {row[0]}, Name: {row[1]}, Email: {row[2]}')

# Close the connection
conn.close()

view raw JSON →