#Encoding:utf-8#!/usr/bin/pythonImportMySQLdb#Open a database connectiondb = MySQLdb.connect ("localhost","testuser","test123","TESTDB" )#get an operation cursor using the cursor () methodcursor =db.cursor ()#SQL UPDATE statementsql ="UPDATE EMPLOYEE SET age = age + 1 WHERE SEX = '%c '"% ('M')Try: #Execute SQL statementcursor.execute (SQL)#commit to database executionDb.commit ()except: #Roll Back when an error occursDb.rollback ()#To close a database connectionDb.close ()Execution transactions
Transaction mechanisms ensure data consistency.
A transaction should have 4 properties: atomicity, consistency, isolation, persistence. These four properties are often called acid properties.
- Atomicity (atomicity). A transaction is an inseparable unit of work, and the operations included in the transaction are either done or not.
- Consistency (consistency). The transaction must be to change the database from one consistency state to another. Consistency is closely related to atomicity.
- Isolation (Isolation). Execution of one transaction cannot be disturbed by other transactions. That is, the operations inside a transaction and the data used are isolated from other transactions that are concurrently executing, and cannot interfere with each other concurrently.
- Persistence (durability). Persistence, also known as permanence (permanence), refers to the fact that once a transaction is committed, its changes to the data in the database should be permanent. The next operation or failure should not have any effect on it.
The transaction for Python DB API 2.0 provides two methods of commit or rollback.
Instance:
# SQL Delete Record statement " DELETE from the EMPLOYEE WHERE age > '%d ' "%" try: # Execute SQL statement cursor.execute (SQL) # Submit to Database db.commit ()except: # rollback When an error occurs db.rollback ()
For a database that supports transactions, in Python database programming, when the cursor is established, an invisible database transaction is automatically started.
Commit () method all the update operations of the cursor, the rollback () method rolls back all operations of the current cursor. Each method starts a new transaction.
Python-mysql Action