码迷,mamicode.com
首页 > 数据库 > 详细

SQL.py

时间:2016-06-26 15:25:02      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

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()

 

SQL.py

标签:

原文地址:http://www.cnblogs.com/feifeidxl/p/5617898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!