計算機科学のブログ

ほしい物リスト

Python - SQL - SQLite - Databases: Getting Organized - select, insert, placeholder

Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly GuidePaul Barry(著)、 O’Reilly Mediaの Chapter 12.(Databases: Getting Organized)、EXERCISE(558/682)の解答を求めてみる。

Jupyter(コード、入出力結果)

webapp/PopulateTables.ipynb

with DBcm.UseDatabase(db_details) as db:
    for file in files:
        name, age, *_ = file.removesuffix('.txt').split('-')
        db.execute(SQL_SELECT, (name, age,))
        if not db.fetchall():
            db.execute(SQL_INSERT, (name, age,))
with DBcm.UseDatabase(db_details) as db:
    db.execute('''select * from swimmers''')
    results = db.fetchall()
results
[(248, 'Hannah', 13),
 (249, 'Darius', 13),
 (250, 'Owen', 15),
 (251, 'Mike', 15),
 (252, 'Abi', 10),
 (253, 'Ruth', 13),
 (254, 'Tasmin', 15),
 (255, 'Erika', 15),
 (256, 'Maria', 9),
 (257, 'Elba', 14),
 (258, 'Ali', 12),
 (259, 'Chris', 17),
 (260, 'Aurora', 13),
 (261, 'Katie', 9),
 (262, 'Alison', 14),
 (263, 'Emma', 13),
 (264, 'Calvin', 9),
 (265, 'Blake', 15),
 (266, 'Bill', 18),
 (267, 'Dave', 17),
 (268, 'Lizzie', 14),
 (269, 'Carl', 15)]