To export a Python DataFrame to an SQL file, you can use the ‘pandas‘ library along with a SQL database engine such as SQLite. Here’s an example using SQLite as the database:
import pandas as pd
from sqlalchemy import create_engine
# Create a sample DataFrame
data = {'Name': ['John', 'Alice', 'Bob'],
'Age': [28, 25, 22],
'City': ['New York', 'San Francisco', 'Seattle']}
df = pd.DataFrame(data)
# Specify the SQLite database file
db_file = 'example.db'
# Create a SQLite engine
engine = create_engine(f'sqlite:///{db_file}')
# Export the DataFrame to SQLite
df.to_sql('example_table', engine, index=False, if_exists='replace')
# Verify the data is in the SQLite database
query = 'SELECT * FROM example_table'
result = pd.read_sql(query, engine)
# Print the result
print(result)
In this example:
- We create a simple DataFrame named ‘
df‘. - We specify the SQLite database file (‘
example.db‘) and create a SQLite engine using the ‘create_engine‘ function from the ‘sqlalchemy‘ library. - We use the ‘
to_sql‘ method of the DataFrame to export it to the SQLite database. The parameters are:'example_table': Name of the table in the database.- ‘
engine‘: The SQLite engine. - ‘
index=False‘: Exclude the DataFrame index from being stored as a separate column in the database. - ‘
if_exists='replace'‘: If the table already exists, replace it.
- We then run a SELECT query (‘
SELECT * FROM example_table‘) to retrieve the data from the SQLite database and print the result.
Make sure to install the necessary libraries if you haven’t already:
pip install pandas sqlalchemy
You can adapt this example for other SQL databases by changing the database engine in the ‘create_engine‘ function and adjusting the connection parameters accordingly.
0 Comments