import sqlite3
conn = sqlite3.connect('food.db')
curs = conn.cursor()
curs.execute('''
CREATE TABLE IF NOT EXISTS food(
id TEXT PRIMARY KEY,
desc TEXT
)
''')
query = 'DELETE FROM food'
print query
curs.execute(query)
query = 'INSERT INTO food VALUES(1, 2)'
print query
curs.execute(query) # sqlite3.IntegrityError: UNIQUE constraint failed: food.id
sqlite3.OperationalError: no such column: A
val = 'a'
query = 'INSERT INTO food VALUES(2, ?)'
print query
curs.execute(query, val)
vals = ['A', 'xyz']
query = 'INSERT INTO food VALUES(?, ?)'
print query
curs.execute(query, vals)
query = 'select * from food'
print query
curs.execute(query)
names = [f[0] for f in curs.description]
print names
for row in curs.fetchall():
for pair in zip(names, row):
print '%s: %s' % pair
print
conn.commit()
conn.close()
food_query.py
import sqlite3, sys
conn = sqlite3.connect('food.db')
curs = conn.cursor()
# run as -> run configurations -> arguments id=1 do not blank!
query = 'select * from food where %s' % sys.argv[1]
print query
curs.execute(query)
names = [f[0] for f in curs.description]
print names
for row in curs.fetchall():
for pair in zip(names, row):
print '%s: %s' % pair
print
conn.commit()
conn.close()
参考:
《python基础教程》