- Python & MySQL - Discussion
- Python & MySQL - Useful Resources
- Python & MySQL - Quick Guide
- Python & MySQL - Handling Errors
- Python & MySQL - Performing Transactions
- Python & MySQL - Using Joins
- Python & MySQL - Sorting Data
- Python & MySQL - Like Clause
- Python & MySQL - Where Clause
- Python & MySQL - Delete Records
- Python & MySQL - Update Records
- Python & MySQL - Select Records
- Python & MySQL - Insert Records
- Python & MySQL - Drop Tables
- Python & MySQL - Create Tables
- Python & MySQL - Select Database
- Python & MySQL - Drop Database
- Python & MySQL - Create Database
- Python & MySQL - Connect Database
- Python & MySQL - Environment Setup
- Python & MySQL - Overview
- Python & MySQL - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python & MySQL - Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durabipty − Once a transaction was committed, the effects are persistent, even after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
Example
You already know how to implement transactions. Here is again similar example −
# Prepare SQL query to DELETE required records sql = "Delete from tutorials_tbl where tutorial_id = 2" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback()
COMMIT Operation
Commit is the operation, which gives a green signal to database to finapze the changes, and after this operation, no change can be reverted back.
Here is a simple example to call commit method.
db.commit()
ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.
Here is a simple example to call rollback() method.
db.rollback()
Disconnecting Database
To disconnect Database connection, use close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your apppcation would be better off calpng commit or rollback exppcitly.
Advertisements