To add a data frame to a SQL database in Python, you can use the Pandas library which provides the pd.to_sql() method that automatically creates a table and inserts the data into it. Alternatively, you can also use the SQLalchemy library to handle the database connection and execute SQL queries.
Here is an example using SQLite3 and Pandas:
main.py326 chars15 lines
In this example, we first create a database connection to a SQLite3 database stored in a file named example.db
. Then, we create a data frame df
containing some sample data. Finally, we use the to_sql()
method to insert the data into a table named people
. The if_exists='replace'
parameter specifies that if the table already exists, it should be dropped and recreated before inserting the data.
Alternatively, you can use SQLalchemy to create a database connection and handle the SQL queries:
main.py408 chars15 lines
In this example, we first create a database connection using SQLalchemy by specifying the connection string sqlite:///example.db
. Then, we create a data frame df
containing some sample data. Finally, we use the to_sql()
method with the con
parameter to insert the data into a table named people
. The if_exists='replace'
parameter specifies that if the table already exists, it should be dropped and recreated before inserting the data. Lastly, we use the dispose()
method to close the connection.
gistlibby LogSnag