return to first page linux journal archive
keywordscontents

Listing 2. Python Transaction Example

def addAttendee(name, seminar, paid):
  # Fetch the number of places left
  cursor.execute('select places_left'
                 ' from Seminars'
                 ' where ID=%s' % (seminar),)
  (places_left, )=cursor.fetchone()
  # If there are no places left, raise exception
  if places_left==0: 
    raise ValueError,'Out of room:#%i' %(seminar,)
  # Add a row to the Attendees table
  cursor.execute("insert into Attendees "
                 "values (?,?,?)",
                 (name, seminar, paid) )
  # Decrease the places_left count of the selected
  # seminar
  cursor.execute("update Seminars set "
                 "places_left=%i where ID=%s"
                 % (places_left-1, seminar) )
  # Commit the changes 	
  db.commit()