From 968bfe613a81ebe2a952c6a339bf6bce7a4f4aa1 Mon Sep 17 00:00:00 2001 From: Anand Date: Wed, 30 Apr 2008 11:43:13 +0000 Subject: [PATCH] edit --- cookbook/trasactions.md | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 cookbook/trasactions.md diff --git a/cookbook/trasactions.md b/cookbook/trasactions.md new file mode 100644 index 00000000..744d832f --- /dev/null +++ b/cookbook/trasactions.md @@ -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.