Python SQLite
SQLite is a lightweight, serverless, and self-contained database engine that allows you to create and manage relational databases within your Python applications. It is widely used for local development, prototyping, and small-scale applications where a full-fledged database server is not required.
Python provides a built-in module called sqlite3 that allows you to interact with SQLite databases. This module provides a simple and intuitive API for performing various database operations such as creating databases, creating tables, inserting data, querying data, updating data, and deleting data.
Here's a basic example that demonstrates some common SQLite operations using Python:
import sqlite3
# Connect to a SQLite database (creates a new database if it doesn't exist)
connection = sqlite3.connect('mydatabase.db')
# Create a cursor object to execute SQL statements
cursor = connection.cursor()
# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
city TEXT
)
''')
# Insert data into the table
cursor.execute("INSERT INTO employees VALUES (1, 'John', 30, 'New York')")
cursor.execute("INSERT INTO employees VALUES (2, 'Alice', 28, 'London')")
connection.commit()
# Query data from the table
cursor.execute("SELECT * FROM employees")
result = cursor.fetchall()
for row in result:
print(row)
# Update data in the table
cursor.execute("UPDATE employees SET age = 31 WHERE id = 1")
connection.commit()
# Delete data from the table
cursor.execute("DELETE FROM employees WHERE id = 2")
connection.commit()
# Close the connection
connection.close()
In the above code, we establish a connection to an SQLite database named mydatabase.db. We create a cursor object to execute SQL statements. We create a table named employees with columns id, name, age, and city. We then perform operations such as inserting data into the table, querying data from the table, updating data in the table, and deleting data from the table.
The sqlite3 module provides methods for executing SQL statements, fetching data, committing changes, and more. It also supports parameterized queries to prevent SQL injection attacks.
SQLite is a powerful and versatile database engine, and the sqlite3 module in Python provides a convenient way to work with SQLite databases in your Python applications. You can refer to the official Python documentation for the sqlite3 module for more details on the available methods and functionalities.