使用数据库有效地执行所有这些操作:
创建并填充数据库:
import sqlite3
a = [['John', 8, 'Student' ],
['Paul', 22, 'Car Dealer'],
['Nick', 30, 'Doctor' ],
['Mark', 66, 'Retired' ]]
conn = sqlite3.connect('so.db')
c = conn.cursor()
c.execute('''CREATE TABLE data
(name text, age int, occupation text)''')
c.executemany('INSERT INTO data VALUES (?,?,?)', a)
conn.commit()
conn.close()
现在在数据库中搜索:
>>> conn = sqlite3.connect('so.db')
>>> c = conn.cursor()
数量rows
:
>>> c.execute('''select count(*) from data''').next()
(4,)
搜索name
:
>>> c.execute('''select * from data where name="Paul"''').fetchall()
[(u'Paul', 22, u'Car Dealer')]
>>> c.execute('''select * from data where name="qwerty"''').fetchall()
[]
搜索age
:
>>> c.execute('''select * from data where age="66"''').fetchall()
[(u'Mark', 66, u'Retired')]
搜索occupation
:
>>> c.execute('''select * from data where occupation="Engineer"''').fetchall()
[]
>>> c.execute('''select * from data where occupation="Doctor"''').fetchall()
[(u'Nick', 30, u'Doctor')]
next
如果您只想True
作为False
输出使用:
>>> bool(next(c.execute('''select * from data where age=36'''), 0))
False
>>> bool(next(c.execute('''select * from data where age=66'''), 0))
True
c.fetchall()
将返回所有匹配的行。