Write a utils.py file for connecting to a SQLite db, querying db, loading results as a pandas dataframe. Do not include any querie strings in the utils.py file. Then show an example of importing functions from utils and making a query with results stored in a dataframe.2 / 2
First, let's create a utils.py
file that contains the necessary functions for connecting to a SQLite database, executing queries, and loading the results into a pandas DataFrame.
utils.py:
pythonCopy codeimport sqlite3
import pandas as pd
def create_connection(db_path):
"""
Creates a connection to the SQLite database specified by the db_path.
:param db_path: The path to the SQLite database file.
:return: The connection object or None if an error occurs.
"""
try:
conn = sqlite3.connect(db_path)
return conn
except sqlite3.Error as e:
print(e)
return None
def execute_query(conn, query):
"""
Executes the given SQL query using the provided connection.
:param conn: The connection object to the SQLite database.
:param query: The SQL query string to execute.
:return: The cursor object after executing the query.
"""
try:
cursor = conn.cursor()
cursor.execute(query)
return cursor
except sqlite3.Error as e:
print(e)
return None
def load_results_as_dataframe(cursor):
"""
Loads the results from a cursor object into a pandas DataFrame.
:param cursor: The cursor object containing the query results.
:return: A pandas DataFrame containing the query results.
"""
columns = [description[0] for description in cursor.description]
return pd.DataFrame(cursor.fetchall(), columns=columns)
def close_connection(conn):
"""
Closes the connection to the SQLite database.
:param conn: The connection object to the SQLite database.
"""
conn.close()
Now, let's create an example script to demonstrate how to import the functions from utils.py
and use them to execute a query and store the results in a DataFrame.
example.py:
pythonCopy codefrom utils import create_connection, execute_query, load_results_as_dataframe, close_connection
# Replace 'your_database.db' with the path to your SQLite database file
db_path = 'your_database.db'
query = "SELECT * FROM your_table_name;"
# Create a connection to the SQLite database
conn = create_connection(db_path)
if conn is not None:
# Execute the query and load the results into a pandas DataFrame
cursor = execute_query(conn, query)
df = load_results_as_dataframe(cursor)
# Close the connection to the SQLite database
close_connection(conn)
# Display the results in the DataFrame
print(df)
else:
print("Unable to connect to the database.")
Replace your_database.db
with the path to your SQLite database file and your_table_name
with the name of the table you want to query. Run the example.py
script to execute the query and display the results in a pandas DataFrame.