Inserting Address Records into the Address Table

To get addresses into the database, we have to transform an instance; of the Address class into a record. Define the format string for the insert entries.

params = """AddrlD, Name, Phone, Email""" insert = """

INSERT INTO

Address

VALUES

Define functions to create an INSERT statement.

def insertAddress(address, statement=None)

11 11 11

Inserts the AddrlD, Name, Phone, Email into a row.

str (id), formatSQLStr(a.name()), formatSQLStr(a.phoneNumber()) formatSQLStr(a.email() )

executeUpdate(insert % values, statement)

print insert % values

Isvoke tie helper function formatSQLStr () to transform the address iaformation irto a strirg that SQL understards.

def formatSQLStr(str):

" ""Formats a string into a SQL string""" str = "'%s'" % str return str

Now we'll add all of our addiess book dioa to the datab ^se (useis like you to dot this for them). For this we need theloadFromFile () fttnction. which rrads the address.dao file ard stores a given address in the Address def loadFromFile() :

11 11 11

Loads the flat file of addresses into the Address table.

a a a from AddressFileUtils import readAddresses dict = readAddresses()

# Create a statement for the database.

# Add all of the addresses to the table.

try:

statement, connection = createStatement()

# Iterate through the collection

# of addresses. Add each address to the

# database.

for address in dict.values():

insertAddress(address, statement)

finally:

connection.close()

Next we add tie following sta1emenis to the main block so we can read loadFromFile () from the commst lire.

from sys import argv

#Process the command line arguments. for arg in argv:

loadFromFile()

To load the data from the file, we run AddressDBUtils.py from the command line with the " 1" option Here's the DOS prompt:

C:\JPython_book\scripts\chap17\AddressBook3>JPython AddressDBUtils.py

Was this article helpful?

0 0

Post a comment