Python SQLite – Select Data from Table
To select data from a SQLite database table using Python, you can execute SQL `SELECT` statements. These statements specify the columns to be retrieved and the conditions for selecting rows from the table. Here’s how you can select data from a table named `employees`:
1. Establish Connection: First, establish a connection to the SQLite database file using the `connect()` function from the `sqlite3` module.
2. Create Cursor: After establishing the connection, create a cursor object using the `cursor()` method.
3. Execute SQL Statement: Use the cursor’s `execute()` method to execute an SQL `SELECT` statement. This statement specifies the columns to be retrieved and any conditions for selecting rows from the table.
4. Fetch Data: After executing the SQL statement, fetch the selected data from the cursor using one of the fetch methods (`fetchone()`, `fetchall()`, or `fetchmany()`).
5. Process Data: Process the fetched data as needed. For example, you can iterate over the rows and print them, or store them in variables for further processing.
6. Close Cursor and Connection: Finally, close the cursor and connection using the `close()` method to release any resources associated with them.
Here’s an example of how to select data from the `employees` table:
“`python
import sqlite3
# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL statement to select data
cursor.execute(‘SELECT * FROM employees’)
# Fetch all selected data
rows = cursor.fetchall()
# Process fetched data
for row in rows:
print(row)
# Close cursor and connection
cursor.close()
connection.close()
“`
In this example:
– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute an SQL `SELECT * FROM employees` statement using the cursor’s `execute()` method to select all columns from the `employees` table.
– We fetch all selected data using the `fetchall()` method and store it in the `rows` variable.
– We iterate over the rows and print each row.
– Finally, we close the cursor and connection.