3.3 KiB
Certainly! Working with SQLite3 in Python involves several key steps, from connecting to a SQLite database to performing database operations and finally closing the connection. Below is a basic outline and explanation of a Python script that uses SQLite3 for database operations. This script demonstrates how to define a database, connect to it, create a table, insert data, query data, and handle transactions with commit/rollback, and finally close the connection.
import sqlite3
# Define and connect to the database
# This will create the database file if it does not already exist
conn = sqlite3.connect('example.db')
# Create a cursor object using the cursor() method
cursor = conn.cursor()
# Define a table
# If the table already exists, this command will be ignored
cursor.execute('''CREATE TABLE IF NOT EXISTS inventory
(item_id INTEGER PRIMARY KEY, name TEXT, quantity INTEGER)''')
# Insert data into the table
cursor.execute('''INSERT INTO inventory (name, quantity)
VALUES ('Apples', 30), ('Bananas', 45), ('Oranges', 20)''')
# Commit the transaction (if necessary)
# If you're performing operations that modify the data, you need to commit
conn.commit()
# Query the database
cursor.execute('''SELECT * FROM inventory''')
for row in cursor.fetchall():
print(row)
# Handling transactions with commit/rollback
try:
# Perform some database operations
cursor.execute('''UPDATE inventory SET quantity = 25 WHERE name = 'Apples' ''')
# More operations...
# Commit if everything is fine
conn.commit()
except sqlite3.Error as e:
# Rollback on error
print(f"An error occurred: {e}")
conn.rollback()
# Close the cursor and connection to the database
cursor.close()
conn.close()
Here's what each part of the script does:
-
Import SQLite3: The
sqlite3module is imported to use SQLite database functionalities. -
Connect to Database: The
connectfunction is used to connect to an SQLite database. It takes the database file name as an argument. If the file doesn't exist, SQLite will create it. -
Creating a Cursor Object: A cursor object is created using the
cursor()method. The cursor is used to execute SQL commands. -
Create Table: The
executemethod of the cursor is used to execute SQL commands. Here, it's used to create a new table if it doesn't already exist. -
Insert Data: Inserts data into the table. SQLite supports inserting multiple records in a single command.
-
Commit Transaction: If you've performed operations that modify the database, you must commit these changes to make them permanent.
-
Query Data: Executes a SELECT statement to fetch all records from the table, which are then printed out.
-
Handling Transactions with Commit/Rollback: Demonstrates error handling in transactions. If an error occurs during a database operation, the changes are rolled back.
-
Close Cursor and Connection: Finally, the cursor and the connection to the database are closed.
This script forms a basic template for performing database operations with SQLite in Python. Depending on your needs, you can modify and expand upon this template, such as by adding more complex queries, using parameters in your SQL commands to avoid SQL injection, and handling more sophisticated error scenarios.