Today I Remember - Python SQLite
Have you ever needed to work with SQLite databases in Python? Perhaps you are dealing with a large dataset or building a web application that requires persistent storage. Whatever your use case, Python’s built-in sqlite3 module makes it easy to read, write, and manipulate SQLite databases.
To get started, you will first need to create a SQL connection to your SQLite database using the sqlite3.connect()
method. This method takes the name of your SQLite database file as an argument and returns a connection object.
Once you have a connection object, you can create a cursor object using the connection.cursor()
method. This cursor object allows you to execute SQL queries against your database and retrieve results.
For example, let us say you have a table named ’table’ in your SQLite database that contains some data you want to process. You could use the following code to retrieve and print all the rows in the table:
import sqlite3
# Create a SQL connection to our SQLite database
connection = sqlite3.connect("example.sqlite")
cursor = connection.cursor()
# The result of a "cursor.execute" can be iterated over by row
for row in cursor.execute('SELECT * FROM table;'):
print(row)
# Be sure to close the connection
connection.close()
This code creates a SQL connection to the example.sqlite
database file, creates a cursor object, executes a SQL query to retrieve all rows from the table table, and prints each row to the console.
When you are finished working with your SQLite database, be sure to close the connection using the connection.close()
method to release any resources held by the connection object.
For more information on how to use the sqlite3 module in Python, check out the official documentation1.