Writing clean Python code for database query involves multiple steps, including setting up the database connection, writing the query, executing it, and then handling the results. Here's a simple example using SQLite, a server-less database that Python can access directly.
python
import sqlite3
def connect_to_database(db_name):
"""Connect to the SQLite database"""
conn = sqlite3.connect(db_name)
return conn
def execute_query(conn, query):
"""Execute a query using the connection"""
cursor = conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
return rows
def main():
"""Main function to setup database connection and execute queries"""
conn = connect_to_database('test.db')
# A simple query to select all from a table called 'students'
query = "SELECT * FROM students"
rows = execute_query(conn, query)
for row in rows:
print(row)
# Don't forget to close the connection when you're done
conn.close()
if __name__ == "__main__":
main()
This is a simple and clean Python code for querying a database.
Please note the following while writing clean Python code for database queries:
Separation of concerns: Separate the logic of connecting to the database and executing queries into different functions. This makes the code more readable and maintainable.
Error handling: The above code does not include error handling. In a real-world scenario, you'd want to include try/except blocks to handle potential errors, such as issues connecting to the database or issues executing your query.
SQL Injection Attacks: Never use Python's string operations to assemble your queries. They make your program vulnerable to an SQL injection attack. Instead, use the DB-API's parameter substitution.
Closing Connections: Always close the connection when you're done with your database operations to free up resources.
Comments: Use comments to explain what your code is doing, especially for more complex queries.