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.

CHAPTER 13 ■ DATABASE SUPPORT 293<br />

Listing 13-1. Importing Data into the Database (importdata.py)<br />

import sqlite<br />

def convert(value):<br />

if value.startswith('~'):<br />

return value.strip('~')<br />

if not value:<br />

value = '0'<br />

return float(value)<br />

conn = sqlite.connect('food.db')<br />

curs = conn.cursor()<br />

curs.execute('''<br />

CREATE TABLE food (<br />

id TEXT PRIMARY KEY,<br />

desc TEXT,<br />

water FLOAT,<br />

kcal FLOAT,<br />

protein FLOAT,<br />

fat FLOAT,<br />

ash FLOAT,<br />

carbs FLOAT,<br />

fiber FLOAT,<br />

sugar FLOAT<br />

)<br />

''')<br />

field_count = 10<br />

markers = ', '.join(['%s']*field_count)<br />

query = 'INSERT INTO food VALUES (%s)' % markers<br />

for line in open('ABBREV.txt'):<br />

fields = line.split('^')<br />

vals = [convert(f) for f in fields[:field_count]]<br />

curs.execute(query, vals)<br />

conn.commit()<br />

conn.close()<br />

When you run this program (with ABBREV.txt in the same directory), it will create a new file<br />

called food.db, containing all the data of the database.<br />

I’d really like to encourage you to play around with this example, using other inputs,<br />

adding print statements, and the like.

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

Saved successfully!

Ooh no, something went wrong!