Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the need to commit explicitly when doing an UPDATE?

Here's my code:

import cx_Oracle

conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
conn.commit()

If I remove the conn.commit(), the table isn't updated. But for select statements, I don't need that conn.commit(). I'm curious why?

like image 727
tshepang Avatar asked May 17 '10 09:05

tshepang


3 Answers

The DB-API spec requires that connecting to the database begins a new transaction, by default. You must commit to confirm any changes you make, or rollback to discard them.

Note that if the database supports an auto-commit feature, this must be initially off.

Pure SELECT statements, since they never make any changes to the database, don't have to have their changes committed.

like image 60
bobince Avatar answered Oct 05 '22 16:10

bobince


commit is used to tell the database to save all the changes in the current transaction.

Select does not change any data so there is nothing to save and thus nothing to commit

See wikipedia for transactions

like image 35
mmmmmm Avatar answered Oct 01 '22 16:10

mmmmmm


Others have explained why a commit is not necessary on a SELECT statement. I just wanted to point out you could utilize the autocommit property of the Connection object to avoid having to manually execute commit yourself:

import cx_Oracle

with cx_Oracle.connect(usr, pwd, url) as conn:
    conn.autocommit = True
    cursor = conn.cursor()
    cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
    cursor.close()

This is especially useful when you have multiple INSERT, UPDATE, and DELETE statements within the same connection.

like image 9
Erik Anderson Avatar answered Oct 04 '22 16:10

Erik Anderson