計算機科学のブログ

ほしい物リスト

Python - SQL - Databases: Getting Organized - with statement, execute method, fetchall method

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(540/682)の解答を求めてみる。

%pip install DMcm --upgrade

で以下のエラーが発生。

This error typically indicates that MariaDB Connector/C, a dependency which
must be preinstalled, is not found.
If MariaDB Connector/C is not installed, see installation instructions
If MariaDB Connector/C is installed, either set the environment variable
MARIADB_CONFIG or edit the configuration file 'site.cfg' to set the
 'mariadb_config' option to the file location of the mariadb_config utility.

ということで、 MariaDB Connector/C をインストールしようと思ったら、LinuxとWindwsのだけでmacOSのが見つからなかった。

Included in MariaDB 10.6.5

MariaDB自体に含まれる みたいだから、デスク容量あんまり使いたくなかったけど、後に役に立つ、使うことも期待してmacportsで丸ごとインストール。

% sudo port install mariadb-11.4
...
%

何かいろいろ設定面倒になったから、pipでPyPIからインストールするんじゃなく GitHubのDM.py を直接利用することに。

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

webapp/CreateDatabaseTables.ipynb

import DBcm
db_details = 'CoachDB.sqlit3'
SQL = '''
create table if not exists swimmers (
    id integer not null primary key autoincrement,
    name varchar(32) not null,
    age integer not null
)
'''
with DBcm.UseDatabase(db_details) as db:
    db.execute(SQL)
with DBcm.UseDatabase(db_details) as db:
    db.execute('pragma tables_list')
    results = db.fetchall()
results
[]