データベースを使用して、これらすべての操作を効率的に実行します。
データベースを作成して入力します。
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()
一致するすべての行を返します。