04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

292 CHAPTER 13 ■ DATABASE SUPPORT<br />

link under the heading “Abbreviated.” You should now get a zip file containing a text file named<br />

ABBREV.txt, along with a PDF file describing its contents. 1 If you have trouble finding this particular<br />

file, any old data will do, of course. Just modify the source code to suit.<br />

The data in the ABBREV.txt file has one data record per line, with the fields separated by<br />

caret (^) characters. The numeric fields contain numbers directly, while the textual fields have<br />

their string values “quoted” with a tilde (~) on each side. Here is a sample line, with parts deleted<br />

for brevity:<br />

~07276~^~HORMEL SPAM ... PORK W/ HAM MINCED CND~^ ... ^~1 serving~^^~~^0<br />

Parsing such a line into individual fields is a simple as using line.split('^'). If a field<br />

starts with a tilde, you know it’s a string and can use field.strip('~') to get its contents. For<br />

the other (numeric) fields, float(field) should do the trick, except, of course, when the field is<br />

empty. The program developed in the following sections will transfer the data in this ASCII file<br />

into your SQL database, and let you perform some (semi-)interesting queries on them.<br />

■Note This example program is intentionally simple. For a slightly more advanced example of database use<br />

in Python, see Chapter 26.<br />

Creating and Populating Tables<br />

To actually create the tables of the database, and to populate them, writing a completely separate<br />

one-shot program is probably the easiest solution. You can run this program once, and then<br />

forget about both it and the original data source (the ABBREV.txt file), although keeping them<br />

around is probably a good idea.<br />

The program shown in Listing 13-1 creates a table called food with some appropriate fields,<br />

reads the file ABBREV.txt, parses it (by splitting the lines and converting the individual fields using<br />

a utility function, convert), and inserts values read from the text field into the database using<br />

an SQL INSERT statement in a call to curs.execute.<br />

■Note It would have been possible to use curs.executemany, supplying a list of all the rows extracted<br />

from the data file. This would have given a minor speedup in this case, but might have given a more substantial<br />

speedup if a networked client-server SQL system were used.<br />

1. At the time of writing, you can get this file from the URL http://www.nal.usda.gov/fnic/foodcomp/<br />

Data/SR17/dnload/sr17abbr.zip.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!