Skip to content

Commit 4f7d8bb

Browse files
authored
DOC: improve explanation of con argument DataFrame.to_sql (pandas-dev#34944)
* DOC: added example of Connection as con argument to to_sql * DOC: fixed styling in to_sql docstring * DOC: fixed styling in to_sql docstring * DOC: fixed styling in to_sql docstring * revert accidental changes * DOC: fixed context manager example in to_sql * DOC: fixed typo in to_sql docstring
1 parent d85b93d commit 4f7d8bb

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

pandas/core/generic.py

+16-7
Original file line numberDiff line numberDiff line change
@@ -2468,7 +2468,7 @@ def to_sql(
24682468
----------
24692469
name : str
24702470
Name of SQL table.
2471-
con : sqlalchemy.engine.Engine or sqlite3.Connection
2471+
con : sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
24722472
Using SQLAlchemy makes it possible to use any DB supported by that
24732473
library. Legacy support is provided for sqlite3.Connection objects. The user
24742474
is responsible for engine disposal and connection closure for the SQLAlchemy
@@ -2556,18 +2556,27 @@ def to_sql(
25562556
>>> engine.execute("SELECT * FROM users").fetchall()
25572557
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
25582558
2559-
>>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
2560-
>>> df1.to_sql('users', con=engine, if_exists='append')
2559+
An `sqlalchemy.engine.Connection` can also be passed to to `con`:
2560+
>>> with engine.begin() as connection:
2561+
... df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
2562+
... df1.to_sql('users', con=connection, if_exists='append')
2563+
2564+
This is allowed to support operations that require that the same
2565+
DBAPI connection is used for the entire operation.
2566+
2567+
>>> df2 = pd.DataFrame({'name' : ['User 6', 'User 7']})
2568+
>>> df2.to_sql('users', con=engine, if_exists='append')
25612569
>>> engine.execute("SELECT * FROM users").fetchall()
25622570
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
2563-
(0, 'User 4'), (1, 'User 5')]
2571+
(0, 'User 4'), (1, 'User 5'), (0, 'User 6'),
2572+
(1, 'User 7')]
25642573
2565-
Overwrite the table with just ``df1``.
2574+
Overwrite the table with just ``df2``.
25662575
2567-
>>> df1.to_sql('users', con=engine, if_exists='replace',
2576+
>>> df2.to_sql('users', con=engine, if_exists='replace',
25682577
... index_label='id')
25692578
>>> engine.execute("SELECT * FROM users").fetchall()
2570-
[(0, 'User 4'), (1, 'User 5')]
2579+
[(0, 'User 6'), (1, 'User 7')]
25712580
25722581
Specify the dtype (especially useful for integers with missing values).
25732582
Notice that while pandas is forced to store the data as floating point,

0 commit comments

Comments
 (0)