@@ -2788,7 +2788,7 @@ def to_sql(
2788
2788
con ,
2789
2789
* ,
2790
2790
schema : str | None = None ,
2791
- if_exists : Literal ["fail" , "replace" , "append" ] = "fail" ,
2791
+ if_exists : Literal ["fail" , "replace" , "append" , "delete_rows" ] = "fail" ,
2792
2792
index : bool = True ,
2793
2793
index_label : IndexLabel | None = None ,
2794
2794
chunksize : int | None = None ,
@@ -2825,12 +2825,13 @@ def to_sql(
2825
2825
schema : str, optional
2826
2826
Specify the schema (if database flavor supports this). If None, use
2827
2827
default schema.
2828
- if_exists : {'fail', 'replace', 'append'}, default 'fail'
2828
+ if_exists : {'fail', 'replace', 'append', 'delete_rows' }, default 'fail'
2829
2829
How to behave if the table already exists.
2830
2830
2831
2831
* fail: Raise a ValueError.
2832
2832
* replace: Drop the table before inserting new values.
2833
2833
* append: Insert new values to the existing table.
2834
+ * delete_rows: If a table exists, delete all records and insert data.
2834
2835
2835
2836
index : bool, default True
2836
2837
Write DataFrame index as a column. Uses `index_label` as the column
@@ -2947,6 +2948,16 @@ def to_sql(
2947
2948
... conn.execute(text("SELECT * FROM users")).fetchall()
2948
2949
[(0, 'User 6'), (1, 'User 7')]
2949
2950
2951
+ Delete all rows before inserting new records with ``df3``
2952
+
2953
+ >>> df3 = pd.DataFrame({"name": ['User 8', 'User 9']})
2954
+ >>> df3.to_sql(name='users', con=engine, if_exists='delete_rows',
2955
+ ... index_label='id')
2956
+ 2
2957
+ >>> with engine.connect() as conn:
2958
+ ... conn.execute(text("SELECT * FROM users")).fetchall()
2959
+ [(0, 'User 8'), (1, 'User 9')]
2960
+
2950
2961
Use ``method`` to define a callable insertion method to do nothing
2951
2962
if there's a primary key conflict on a table in a PostgreSQL database.
2952
2963
0 commit comments