SQL.py

Posted *飞飞*

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL.py相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

SQL.py

python spark-sql-application.py

python spark-sql-ranking.py

python spark-sql-aggregations.py

python spark-sql-operations.py

python spark-sql-sorting.py