How to insert a pandas framework into an existing table in a database?

I use sqlalchemypandas to query the postgres database and then paste the conversion results into another table in the same database. But when I do, df.to_sql('db_table2', engine)I get this error message: ValueError: Table 'db_table2' already exists.I noticed that he wants to create a new table. How to insert pandas dataframe into an existing table?

df = pd.read_sql_query('select * from "db_table1"',con=engine)
#do transformation then save df to db_table2
df.to_sql('db_table2', engine)

ValueError: Table 'db_table2' already exists
+4
source share
1 answer

use the if_exists parameter :

df.to_sql('db_table2', engine, if_exists='replace')

or

df.to_sql('db_table2', engine, if_exists='append')

from docstring:

"""
if_exists : {'fail', 'replace', 'append'}, default 'fail'
    - fail: If table exists, do nothing.
    - replace: If table exists, drop it, recreate it, and insert data.
    - append: If table exists, insert data. Create if does not exist.
"""
+12
source

Source: https://habr.com/ru/post/1649269/


All Articles