Skip to content

Commit

Permalink
docs: include option 'delete_rows' in docstrings. fixed the doctest s…
Browse files Browse the repository at this point in the history
…uite after adding a new example using 'delete_rows' to it.
  • Loading branch information
gmcrocetti committed Feb 25, 2025
1 parent 10762c6 commit 4b5338e
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2788,7 +2788,7 @@ def to_sql(
con,
*,
schema: str | None = None,
if_exists: Literal["fail", "replace", "append"] = "fail",
if_exists: Literal["fail", "replace", "append", "delete_rows"] = "fail",
index: bool = True,
index_label: IndexLabel | None = None,
chunksize: int | None = None,
Expand Down Expand Up @@ -2825,12 +2825,13 @@ def to_sql(
schema : str, optional
Specify the schema (if database flavor supports this). If None, use
default schema.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
if_exists : {'fail', 'replace', 'append', 'delete_rows'}, default 'fail'
How to behave if the table already exists.
* fail: Raise a ValueError.
* replace: Drop the table before inserting new values.
* append: Insert new values to the existing table.
* delete_rows: If a table exists, delete all records and insert data.
index : bool, default True
Write DataFrame index as a column. Uses `index_label` as the column
Expand Down Expand Up @@ -2900,6 +2901,7 @@ def to_sql(
--------
Create an in-memory SQLite database.
>>> import pandas as pd
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite://', echo=False)
Expand Down Expand Up @@ -2933,7 +2935,7 @@ def to_sql(
>>> df2.to_sql(name='users', con=engine, if_exists='append')
2
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM users")).fetchall()
... conn.execute(text("SELECT * FROM users")).fetchall() # doctest: +NORMALIZE_WHITESPACE
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
(0, 'User 4'), (1, 'User 5'), (0, 'User 6'),
(1, 'User 7')]
Expand All @@ -2947,6 +2949,16 @@ def to_sql(
... conn.execute(text("SELECT * FROM users")).fetchall()
[(0, 'User 6'), (1, 'User 7')]
Delete all rows before inserting new records with ``df3``
>>> df3 = pd.DataFrame({"name": ['User 8', 'User 9']})
>>> df3.to_sql(name='users', con=engine, if_exists='delete_rows',
... index_label='id')
2
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM users")).fetchall()
[(0, 'User 8'), (1, 'User 9')]
Use ``method`` to define a callable insertion method to do nothing
if there's a primary key conflict on a table in a PostgreSQL database.
Expand Down

0 comments on commit 4b5338e

Please sign in to comment.