Python - SQLite - Databases: Getting Organized - placeholder
Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly Guide、 Paul Barry(著)、 O’Reilly Mediaの Chapter 12.(Databases: Getting Organized)、SHARPEN YOUR PENCIL(560/682)の解答を求めてみる。
Jupyter(コード、入出力結果)
PopulateTables.ipynb
import os
import DBcm
db_details = 'CoachDB.sqlite3'
FOLDER = 'swimdata'
files = os.listdir(FOLDER)
files.remove('.DS_Store')
SQL_SELECT = '''
select * from events
where distance = ? and stroke = ?
'''
SQL_INSERT = '''
insert into events
(distance, stroke)
values
(?, ?)
'''
with DBcm.UseDatabase(db_details) as db:
for filename in files:
_, _, distance, stroke = filename.removesuffix('.txt').split('-')
db.execute(SQL_SELECT, (distance, stroke,))
if not db.fetchall():
db.execute(SQL_INSERT, (distance, stroke,))
with DBcm.UseDatabase(db_details) as db:
db.execute('select * from events')
results = db.fetchall()
results
[(1, '100m', 'Free'),
(2, '100m', 'Back'),
(3, '100m', 'Fly'),
(4, '50m', 'Back'),
(5, '200m', 'Free'),
(6, '200m', 'Back'),
(7, '50m', 'Free'),
(8, '50m', 'Breast'),
(9, '200m', 'IM'),
(10, '100m', 'Breast'),
(11, '400m', 'Free'),
(12, '50m', 'Fly'),
(13, '200m', 'Breast')]