Coding Ref

How to write a Pandas DataFrame to SQL

How to write a Pandas DataFrame to SQL

To write a Pandas dataframe to a SQL database, you can use the to_sql() method of the dataframe. This method allows you to specify the name of the SQL table to which the data should be written, as well as the name of the SQL database engine to use for writing the data.

Example

Here's an example of using the to_sql() method to write a Pandas dataframe to a SQL database:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3],
                   "B": [4, 5, 6]})

# write the dataframe to a SQL database
# using the SQLite database engine
df.to_sql("my_table", con=sqlite3.connect("my_database.db"),
           if_exists="replace")

This will write the data from the dataframe to a SQLite database, using the SQLite database engine.

The data will be written to a table named "my_table" in the database, and any existing data in the table will be replaced with the data from the dataframe.

You can also use the to_sql() method to write the data from the dataframe to a specific schema in the SQL database.

For example:

main.py
# write the dataframe to a SQL database
# using the SQLite database engine, and
# specifying the schema to which the data should be written
df.to_sql("my_table", con=sqlite3.connect("my_database.db"),
           schema="my_schema", if_exists="replace")

This will write the data from the dataframe to the "my*schema" schema in the SQLite database, using the SQLite database engine.

You'll also like

Related tutorials curated for you

    How to join two DataFrames in Pandas

    What is idxmax() in Pandas?

    How to convert string to float in Pandas

    What is isna() in Pandas?

    How to convert Pandas timestamp to datetime

    How to add an empty column to a Pandas DataFrame

    How to convert a series to a NumPy array in Pandas

    How to find the mode in a Pandas DataFrame

    What is .notnull in Pandas?

    How to shuffle data in Pandas

    How to calculate the standard deviation in Pandas DataFrame

    How to select multiple columns in Pandas