Skip to content

Commit

Permalink
edit
Browse files Browse the repository at this point in the history
  • Loading branch information
anandology committed Jan 5, 2011
1 parent b26f35f commit 968bfe6
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions 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.

0 comments on commit 968bfe6

Please sign in to comment.