I use the TO_SQL function from pandas to insert data from DF into a table in Oracle. I would like to check after completing the action the amount of records append to the table. can it be done and how? Thanks
Asked
Active
Viewed 1,460 times
1 Answers
1
pandas.DataFrame.to_sql
returns the amount of rows affected automatically.
amount_of_rows = pd.to_sql(name, connection)
# Setting it to 0 if the database returned no rows.
if not amount_of_rows:
amount_of_rows = 0
# Printing out the amount.
print(f"{amount_of_rows} rows were inserted.")
Will output 'X rows were inserted' if the query ran successfully.
P.S: Returns are not supported in versions prior to 1.4.0.

Mohammad Ayoub
- 379
- 2
- 9
-
1The return could be None, in which case you want to map it to 0. – Learning is a mess Mar 01 '22 at 10:45
-
when i try it i always got none Even if there were rows inserted in the table Maybe I did not understand something, what do you mean by pd.to_sql(**query**) – Amir Mar 01 '22 at 11:37
-
@Amir query refers to the insert query that you're running. Pandas returns the amount of rows affected by the query when using to_sql as seen in its documentation. – Mohammad Ayoub Mar 01 '22 at 11:41
-
@Mohammad I just saw it in the literature, but what's weird to me is when I run my command (**df.to_sql ('table_name', conn, if_exists = 'append', index = False)**) I do not get an output of the number of rows ... Do you have any idea? and if i run the command with print(command) i got **none** – Amir Mar 01 '22 at 11:46
-
1I understood the problem. I had an old pandas version. Thank you @Mohammad – Amir Mar 01 '22 at 12:48
-
Updated the answer accordingly, thanks @Amir – Mohammad Ayoub Mar 01 '22 at 13:17