Summary: in this tutorial, you will learn how to use the Python cx_Oracle API to delete data from a table.
To delete data from a table, you use the following steps:
- First, connect to the Oracle Database by creating a new
Connection
object. - Second, create a new
Cursor
object from theConnection
object by calling theConnection.Cursor()
method. - Third, execute a
DELETE
statement by calling theCursor.execute()
method. - Fourth, call the
Connection.commit()
method to apply the changes to the database. If you forget to call theConnection.commit()
method, you will see that the change will not take effect. - Finally, release the
Cursor
andConnection
objects by calling theCursor.close()
andConnection.close()
method respectively. You can also use thewith
block to release these objects automatically.
The following code illustrates how to delete a row from the billing_headers
table based on a specific billing number.
import oracledb
from connect import connect
import logging
def delete(billing_no: int) -> bool:
sql = '''DELETE FROM billing_headers WHERE billing_no = :billing_no'''
try:
with connect() as connection:
with connection.cursor() as cursor:
params = {
'billing_no': billing_no
}
cursor.execute(sql, params)
connection.commit()
return True
except oracledb.Error as e:
error_message = f"Oracle database error during billing deletion for billing_no {billing_no}: {e}"
logging.error(error_message)
raise
except Exception as e:
error_message = f"An unexpected error occurred during billing deletion for billing_no {billing_no}: {e}"
logging.critical(error_message)
raise
if __name__ == '__main__':
delete(1)
Code language: Python (python)
Here are the contents of the billing_headers
table after executing the program:
SELECT * FROM billing_headers;
Code language: Python (python)

As you can see clearly from the output, the row whose billing_no
is 1 has been removed. It means that the program works as expected.
In this tutorial, you have learned how to use the python-oracledb API to delete data in a table.
Was this tutorial helpful?