Lie Hetland book: Beginning Python..

Vittorio renmybiru at
Mon Nov 7 19:17:07 CET 2005

I am reading "Beginning Python from Novice to Professional" and the book 
is really awesome. Nonetheless on ch 13 "Database Support" I found this 
code to import data (in a txt file) into a SQLite Database:

#this was corrected because original "import sqlite" does not work
from pysqlite2 import dbapi2 as sqlite

#this function strips the txt file from special chars
def convert(value):
    if value.startswith('~'):
        return value.strip('~')
    if not value:
        value = '0'
    return float(value)

conn = sqlite.connect('food.db')
curs = conn.cursor()

  id         TEXT       PRIMARY KEY,
  desc       TEXT,
  water      FLOAT,
  kcal       FLOAT,
  protein    FLOAT,
  fat        FLOAT,
  ash        FLOAT,
  carbs      FLOAT,
  fiber      FLOAT,
  sugar      FLOAT

field_count = 10

#following is the line I suspect mistyped
markers = ', '.join(['%s']*field_count)

query = 'INSERT INTO food VALUES (%s)' % markers

for line in open('ABBREV.txt'):
    fields = line.split('^')
    vals = [convert(f) for f in fields[:field_count]]
    #the following line raises error


The error was "Traceback (most recent call last):
  File "C:\Python24\", line 39, in ?
pysqlite2.dbapi2.OperationalError: near "%": syntax error"

After two hours of trying (did I say I am a beginner?) and after some 
documentation about PySqlite I suspect the error is in:
markers = ', '.join(['%s']*field_count)

I think Magnus intended:
markers = ', '.join(['?']*field_count)

Did I found an errata or my Python is still too green?

More information about the Python-list mailing list