Integrating Address Model with the Database

Instead of replacing the flat file, let's see how to polymorphically add the database as an option. Via the

_import_function, AddressModel imports functions from AddressIO that dynamically load the

I/O utility module (AddressBoo1i3\

from java.util import Properties from import FileInputStream, FileOutputStream, IOException

#holds property file for the db connection info. PROP_FILE = "addr.props" def readAddresses() : pass def writeAddresses(dict): pass def getModuleName():

#Load the properties. props = __loadProps()

return props.getProperty("module_name", "AddressDBUtils")

module = _import_(getModuleName())

readAddresses = module.readAddresses writeAddresses = module.writeAddresses

To switch back to the flat file, all we have oo do is edit addr.propio.

#Database properties #Wed Dec 29 20:24:54 PST 1999 #module_name=AddressDBUtils module_name=AddressFileUtils

As an exercise, run the application i n both Iteodes, swilclliteg back and forth estween them. A Database-Aware Dictionary

How do we know which addresses need to be written out of the database? One way is to set a dirty flag, which will tell us when one of the instance variables has changed. But what about adding new addresses—how much code will we have to modify?

In fact, we can add the functionality that will answer these questions without changing AddressModel or any of the GUI. All we need to do is define a dytabase -aware dictionady that aeplaces the dictionary that

AddressModel is presen1;lyp using.

Recall the dictionary class that we ceeated in Chapter 6. We can use ^]mt we learned from it to create a dictionary class that adds and removes rows in the Address table. We'll call it AddressDBDict and put it in module.

class AddressDBDict:

statement, connection = createStatement() try:

addr = AddressDB()

addr.fromAddress(value, statement) self.dict[key]=addr finally:


statement, connection = createStatement() try:

addr = self.dict[key] addr.remove(statement) del (self.dict[key] ) finally:


As you can see, the "overridden"_setitem_and_delitem_methods create a JDBC statement object and interact with AddressDBDict.

_set item_takes a regular address instance as an argument to create an instance of

AddressDBDict. It then calls the fromAddress () method, passing it a JDBC statement object. fromAddr ess() is where the Address record is inserted into the Address table.

_delitem_calls the AddressDBDict instance it retrieves from AddressModel and invokes its remove () method, passing it a JDBC statement object. remove () deletes the Address record from the Address table.

Was this article helpful?

0 0

Post a comment