RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Fast, Easy Database Access with Python : Page 2

You don't have to keep writing the same old database access code over and over again—instead, it's simple to roll your own database wrapper and use Python syntax to retrieve, search, and update data. Implement the classes and methods shown here to speed up your Python database development process.

Determining Data Length
Something important was missing from the code mentioned so far. Many programs want to know how much data needs to be processed. Most search programs return this with the results, such as "results 80 to 100 of 487." That 487 is important to many search engine users. Luckily, the length operator in Python is easy to implement. Simply add the following to the Table class:
def __len__(self):
   self.dbc.execute("select count(*) from %s" % (self.name))
   r = int(self.dbc.fetchone()[0])
   return r
This will make the function len(books) return the number of items in the table, so you can loop over the entire data set or at least tell the user how much data exists:
for i in xrange(len(books)):
   print books[i] 
Iterating Through Rows
The loop in the previous example was better, but it could have been simpler still. Python supports iterators, which would have been a little easier. It should be possible to process every item in a table with syntax such as:
for book in books:
   print book
This is simple to do, but first it would be a good idea to refactor a little. The Table class will be doing a lot of database queries, and pumping all those queries through one function will help make debugging easier. First, add a self.debug = 1 line to the Table's __init__() function, and then add a method for queries:
def _query(self, q):
   if self.debug: print "Query: %s" % (q)
To add iteration, simply add two methods to the Table class: __iter__() and next(). The class does not need to be derived from a built-in iterator type, it merely needs to implement the same policies. This "policy over mechanism" theme is common in Python. It provides most of the same benefits as more strict languages, without losing flexibility. Adding the following code turns the Table class into an iterable object:
def __iter__(self):
   "creates a data set, and returns an iterator (self)"
   q = "select * from %s" % (self.name)
   return self  # an Iterator is an object 
   # with a next() method

def next(self):
   "returns the next item in the data set, 
      or tells Python to stop"
   r = self.dbc.fetchone()
   if not r:
      raise StopIteration
   return r
By adding this code, the Table class now acts like an iterator, allowing you to use the easy syntax at the beginning of this section.

Putting the concepts of an idea, such as database access, into simpler terms enables still more and better innovations. For example, a car engine is a very complicated device with countless parts and design considerations. It takes a lot of work to fully describe an engine, and to attach it to wheels to make a car. But once you fully understand the concept of an engine, you no longer need to describe it in detail. It becomes sufficient to say "an engine with wheels." Then, after building such a car, you can easily create new concepts by reusing the same old engine ideas. Perhaps after the car, you decide to attach a blade and build a lawn mower. And then, attach wings and a propeller to make a plane. Creating these new things would be vastly more difficult if you had to re-create the concept of an engine each time. Or, in this case, if you had to keep writing the same code over and over, each time you needed to perform an operation you've done before.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date