Database Query Operations
Query Types in SQLite3
SQLite3 supports various query operations to interact with database records:
Query Type |
Purpose |
SELECT |
Retrieve data from tables |
INSERT |
Add new records to tables |
UPDATE |
Modify existing records |
DELETE |
Remove records from tables |
Basic SELECT Queries
import sqlite3
## Establish database connection
conn = sqlite3.connect('labex_database.db')
cursor = conn.cursor()
## Create sample table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT,
department TEXT,
salary REAL
)
''')
## Insert sample data
employees_data = [
('John Doe', 'Engineering', 75000),
('Jane Smith', 'Marketing', 65000),
('Mike Johnson', 'Sales', 55000)
]
cursor.executemany('INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)', employees_data)
conn.commit()
## Simple SELECT query
cursor.execute('SELECT * FROM employees')
print(cursor.fetchall())
## Filtered SELECT query
cursor.execute('SELECT name, salary FROM employees WHERE department = ?', ('Engineering',))
print(cursor.fetchall())
Query Operation Flow
graph TD
A[Establish Connection] --> B[Create Cursor]
B --> C[Prepare SQL Query]
C --> D[Execute Query]
D --> E[Fetch Results]
E --> F[Process Data]
F --> G[Close Connection]
Advanced Query Techniques
Parameterized Queries
def get_employees_by_department(department):
cursor.execute('SELECT * FROM employees WHERE department = ?', (department,))
return cursor.fetchall()
## Safe way to prevent SQL injection
results = get_employees_by_department('Engineering')
Aggregate Functions
## Calculate average salary
cursor.execute('SELECT AVG(salary) FROM employees')
average_salary = cursor.fetchone()[0]
print(f'Average Salary: ${average_salary:.2f}')
## Count employees per department
cursor.execute('SELECT department, COUNT(*) FROM employees GROUP BY department')
department_counts = cursor.fetchall()
Complex Query Operations
JOIN Queries
## Example of a JOIN query (assuming multiple related tables)
cursor.execute('''
SELECT employees.name, departments.dept_name
FROM employees
JOIN departments ON employees.department = departments.dept_name
''')
- Use indexes for frequently queried columns
- Limit result sets with
LIMIT
clause
- Avoid unnecessary full table scans
Query Result Handling Methods
Method |
Description |
fetchone() |
Retrieves next row of query result |
fetchall() |
Retrieves all remaining rows |
fetchmany(size) |
Retrieves specified number of rows |
Best Practices with LabEx Recommendations
- Always use parameterized queries
- Close database connections after use
- Handle potential exceptions
- Use context managers for database operations
## Recommended connection management
with sqlite3.connect('labex_database.db') as conn:
cursor = conn.cursor()
## Perform database operations
conn.commit()
Closing Database Connection
## Proper connection closure
conn.close()
By mastering these database query operations, developers can efficiently manage and manipulate SQLite3 databases in their Python applications.