Python Database Delete Operation

Delete in Python

Any valid DML query can be written and executed through Python. For example,

CODE/PROGRAM/EXAMPLE
import cx_Oracle
	con = cx_Oracle.Connection('user/pswd@192.168.2.1/john')
	cur = cx_Oracle.Cursor(con)
	cur.execute(“DELETE FROM Computer WHERE CompId=100”)
	print(cur.rowcount)
	cur.close()
	con.close()

The cursor object has a rowcount attribute which is used to get the number of rows affected by the last query.

Commiting a transaction

All DML statement transactions are not auto committed by default. Thus any DML operations done through Python will be lost once the connection is closed. To ensure that the DML operations are not lost after the connection, the commit() method has to be invoked on the connection object.

CODE/PROGRAM/EXAMPLE
import cx_Oracle
	con = cx_Oracle.Connection('user/pswd@192.168.2.1/john')
	cur = cx_Oracle.Cursor(con)
	cur.execute(“DELETE FROM Computer WHERE CompId=100”)
	print(cur.rowcount)
	cur.close()
	con.commit(); #Invoking commit method
	con.close()

Demo

Try out the code and observe the results.

CODE/PROGRAM/EXAMPLE
import cx_Oracle
	con = cx_Oracle.Connection('user/pswd@192.168.2.1/john')
	cur = cx_Oracle.Cursor(con)
	parameter=“100”
	query=“DELETE FROM Computer WHERE CompId=”+parameter
	cur.execute(query)
	print(cur.rowcount)
	cur.close()
	con.commit();
	con.close()
#Delete_in_Python #database_delete_operation_in_python

(New page will open, for Comment)

Not yet commented...