import sqlite3,sys 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 IF NOT EXISTS food( id TEXT PRIMARY KEY, desc TEXT, water FLOAT, fat FLOAT, fiber FLOAT, sugar FLOAT ) ‘‘‘) insert_query=‘INSERT INTO food VALUES(?,?,?,?,?,?)‘ for line in open(‘ABBREV.txt‘): fields=line.split(‘^‘) field_count=len(fields) print(fields) vals=[convert(f) for f in fields[:field_count]] curs.execute(insert_query,vals) conn.commit() select_all=‘SELECT * FROM food‘ curs.execute(select_all) print(curs.fetchall()) select_str=‘fat<=100 AND fiber>=10 AND sugar ORDER BY sugar‘ try: if sys.argv[1]: select_str=sys.argv[1] print(‘\n‘,sys.argv,‘\n‘) except: pass #命令行调用,windows下SQL.py要加引号 #python SQL.py ‘fat<=100 AND fiber>=10 AND sugar ORDER BY sugar‘ print(select_str) select_query=‘SELECT * FROM food WHERE %s‘ % select_str curs.execute(select_query) names=[f[0] for f in curs.description] name=[f for f in curs.description] print(name) for row in curs.fetchall(): for pair in zip(names,row): print(‘%s:%s‘ % pair) conn.close()
时间: 2024-10-10 05:32:41