Create Lightweight Database with Python: SQLite3

SQLite is a lightweight, file-based relational database management system (RDBMS) that is widely used in various applications due to its simplicity and efficiency. SQLite3 is the Python module that provides an interface to interact with SQLite databases.

Here’s a brief overview of using SQLite3 in Python:

Installation:

You don’t need to install SQLite separately, as it is included in the Python standard library. However, you can install the SQLite3 module using:

pip install db-sqlite3

Connecting to a Database:

You can connect to an SQLite database using the sqlite3.connect() method. If the database file does not exist, it will be created.

import sqlite3

# Connect to a database or create it if it doesn’t exist
conn = sqlite3.connect(‘example.db’)

Creating a Table:

You can create tables using the execute() method with an SQL CREATE TABLE statement.

# Create a table
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

Inserting Data:

You can insert data into the table using the execute() method with

# Insert data
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('John Doe', 25))

Querying Data:

You can execute queries using the execute() method and fetch the results using methods like fetchone() or fetchall().

# Query data
cursor = conn.execute(“SELECT * FROM users WHERE age > 21”)
for row in cursor.fetchall():

print(row)

Committing Changes and Closing the Connection:

After making changes, you should commit them using the commit() method, and then close the connection.
# Commit changes and close connectionconn.commit()
conn.close()

Using Context Manager:

You can use the with statement to ensure that the connection is properly closed, even if an exception occurs.with sqlite3.

connect(‘example.db’) as conn:
# Perform database operations
cursor = conn.execute(“SELECT * FROM users”)
for row in cursor.fetchall():
print(row)

This is a basic introduction to using SQLite3 with Python. For more advanced operations, you can explore features such as transactions, updating records, deleting records, and more. The SQLite documentation and the Python sqlite3 module documentation are valuable resources for detailed information and examples.

Leave a Reply