Exporting Pandas DataFrame to PostgreSQL table
Start your free 7-days trial now!
Consider the following DataFrame:
A B0 3 a1 4 b
To connect with the PostgreSQL database, we must use the create_engine(~)
method of the sqlalchemy
library:
from sqlalchemy import create_engineengine = create_engine('postgresql://postgres@localhost:5432/test_db')
Here:
we are connecting to a PostgreSQL database called
test_db
, which is hosted on our local machine (localhost
) on the default port5432
.The user that we log in as is the default superuser
postgres
.
If you are using a Mac and run into problems when connecting with the database, please consult our troubleshooting sectionlink here.
To connect with your PostgreSQL server with a password or to connect with a remote server, please consult the guide here.
To save our DataFrame as a table called my_table
in our PostgreSQL database, use the to_sql(~)
method of the DataFrame:
df.to_sql('my_table', con=engine)
If a table with the name 'my_table'
already exists, the above will throw an error. To replace the existing my_table
instead:
df.to_sql('my_table', con=engine, if_exists='replace')
To confirm that our table has been created:
SELECT * FROM my_table;
index | A | B -------+---+--- 0 | 3 | a 1 | 4 | b(2 rows)