#根据文件ABBREV.txt创建数据库
import sqlite3
def convert(value):
if value.startswith('~'):
return value.strip('~')
if not value:
value = '0'
return float(value)
conn = sqlite3.connect('food.db')
curs = conn.cursor()
curs.execute('''
CREATE TABLE food(
id TEXT PRIMARY KEY,
desc TEXT,
water FLOAT,
kcal FLOAT,
protein FLOAT,
fat FLOAT,
ash FLOAT,
carbs FLOAT,
fiber FLOAT,
sugar FLOAT
)
''')
query = 'INSERT INTO food VALUES (?,?,?,?,?,?,?,?,?,?)'
for line in open('ABBREV.txt'):
fields = line.split('^')
vals = [convert(f) for f in fields[:10]]
curs.execute(query,vals)
conn.commit()
conn.close()
#运行完上面的程序,再运行下面的数据库查询程序
import sqlite3,sys
conn = sqlite3.connect('food.db')
curs = conn.cursor()
query = 'SELECT * FROM food WHERE %s' % sys.argv[1:] #书上是sys.argv[1],报错IndexError: list index out of range
print query
curs.execute(query)
names = [f[0] for f in curs.description]
for row in curs.fetchall():
for pair in zip(names,row):
print '%s:%s' % pair
print
#在解释器上运行上面的数据库查询程序,报错信息如下:
SELECT * FROM food WHERE []
Traceback (most recent call last):
File "H:\PythonProgram\food_query.py", line 8, in
curs.execute(query)
OperationalError: no such column:
#ABBREV.txt截图