Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

edit

  • Loading branch information...
commit 968bfe613a81ebe2a952c6a339bf6bce7a4f4aa1 1 parent b26f35f
Anand Chitipothu anandology authored
Showing with 62 additions and 0 deletions.
  1. +62 −0 cookbook/trasactions.md
62 cookbook/trasactions.md
View
@@ -0,0 +1,62 @@
+---
+layout: default
+title: How to use database transactions
+---
+
+# How to use database transactions
+
+### Problem
+
+How to use database transactions
+
+
+### Solution
+
+The web.DB class has a method `transaction` which returns a transaction object. The transaction object can be used to commit or rollback a transaction.
+
+ import web
+
+ db = web.databse(dbn="postgres", db="webpy", user="foo", pw="")
+ t = db.transaction()
+ try:
+ db.insert('person', name='foo')
+ db.insert('person', name='bar')
+ except:
+ t.rollback()
+ raise
+ else:
+ t.commit()
+
+With python 2.5+, transaction can be used as with statement also.
+
+ db = web.databse(dbn="postgres", db="webpy", user="foo", pw="")
+
+ with db.transaction():
+ db.insert('person', name='foo')
+ db.insert('person', name='bar')
+
+
+It is also possible to have nested transactions.
+
+ def post(title, body, tags):
+ t = db.transaction()
+ try:
+ post_id = db.insert('post', title=title, body=body)
+ add_tags(post_id, tags)
+ except:
+ t.rollback()
+ else:
+ t.commit()
+
+ def add_tags(post_id, tags):
+ t = db.transaction()
+ try:
+ for tag in tags:
+ db.insert('tag', post_id=post_id, tag=tag)
+ except:
+ t.rollback()
+ else:
+ t.commit()
+
+
+Nested transactions are ignored for sqlite as they are not supported.
Please sign in to comment.
Something went wrong with that request. Please try again.