🔰

SQLAlchemyでシンプルランキング

に公開

SQLAlchemyでシンプルランキング

今回は、"SQLAlchemy"で簡単なランキングを作ります。

SQLiteは、1つのデータベースを、1つのファイルとして管理します。
出力されたファイルは、次のような専用のソフトウェアで中身を確認すると便利です。
DB Browser for SQLite

※完成コードは最後に記述してあります。

1, モジュールを用意する

作業用フォルダに、実行用の"main.py"と、
データベースにアクセスする処理をまとめる、"util_db.py"ファイルを用意します。

フォルダ構成は次の通りです。

フォルダ構成
作業用フォルダ/
 ├ main.py <- メインのプログラム
 └ util_db.py <- データベース用のプログラム

2, "SQLAlchemy"のインストール

"SQLAlchemy"は、サードパーティ製のモジュールなので、別途インストールが必要です。

コマンド(Macの場合)
$ python3 -m pip install sqlalchemy
コマンド(Winの場合)
$ python -m pip install sqlalchemy

3, SQLAlchemyを使ったCRUDパターン

CRUDとは、Create・Read・Update・Delete の4つの基本操作の頭文字です。

"util_db.py"ファイルに、必要なモジュールのインポート、
そして、"MyDB"クラスを用意します。

"コンストラクタ"では、データベースのファイル名を引数として受け取り、
"create_engine()"で"SQLAlchemy"の本体を作ります。
("echo=True"を指定すると、実行されるSQL文がコンソールに表示されます)

同時に、"sessionmaker()"で、データベースへのアクセス用セッションを作るオブジェクトを用意します。

最後に、"create_all()"関数でエンジンを渡すと、テーブルが作成されます。
(データベース内に、まだ存在しないテーブルだけが作成されます)

"MyDB"クラスの初期状態は次のとおりです。

util_db.py(抜粋)
import datetime
import os
from sqlalchemy import (
    create_engine,
    Column,
    Integer,
    select,
    String
)
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker

class MyDB():

    def __init__(self, path):
        """ コンストラクタ """
        self.dir_base = os.path.dirname(__file__)
        self.db_path = "sqlite:///" + os.path.join(self.dir_base, path)
        # Engine, Session
        self.db_engine = create_engine(self.db_path, echo=True)
        self.db_session = sessionmaker(bind=self.db_engine)
        Base.metadata.create_all(self.db_engine) # テーブルを作る

    # CRUD(Create)
    def insert_record(self, name, comment, score):
        """ データを追加する """
        pass

    # CRUD(Read)
    def read_records(self, limit=10):
        """ データを読み込む(limit件数まで) """
        pass

    def read_record(self, uid):
        """ データを読み込む(1件) """
        pass

    # CRUD(Update)
    def update_record(self, uid, name, comment, score):
        """ データを更新する(1件) """
        pass

    # CRUD(Delete)
    def delete_record(self, uid):
        """ データを削除する(1件) """
        pass

    # Time
    def get_time(self):
        """ 現在日時を取得する """
        return datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")

4, ORMを定義する

SQLAlchemyでは、"ORM(Object Relation Mapping)"という仕組みで、データベースにアクセスします。
(SQL文でアクセスすることもできます)

先ずは、"util_db.py"に、次のようにして、"declarative_base()"を継承した"Record"クラスを定義します。

このクラスは、簡単なランキング用として、
テーブル名を"ranking"とし、
以下のようにシンプルなカラムを定義しています。

カラム名 意味 例
uid 通し番号 1,2,3...などの連番
name ユーザー名 Alex
comment コメント I'm champion!!
score スコア 123
time_stamp 登録時刻 1970/01/01 00:00:00
util_db.py(抜粋)
# ORM
Base = declarative_base()
class Record(Base):

    # Table
    __tablename__ = "ranking"
    # ID
    uid = Column(Integer, primary_key=True, autoincrement=True)
    # Name
    name = Column(String(12), nullable=False)
    # Comment
    comment = Column(String(24), nullable=False)
    # Score
    score = Column(Integer, nullable=False)
    # Timestamp
    time_stamp = Column(String(24), nullable=False)

    def __str__(self):
        return "uid:{0}, name:{1}, comment:{2}, score:{3}, time_stamp:{4}".format(
            self.uid, self.name, self.comment, self.score, self.time_stamp)

5, CRUD処理を実装する

"MyDB"クラスに、CRUD処理を実装していきます。

5-1, データの追加(Create)

"insert_record()"メソッドでは、テーブルにデータを追加します。

with self.db_session() as session:に注目してください。
この部分で一時的にセッションを作り、テーブルにデータを追加、コミットを行います。
これらの処理の実行後、自動的にセッションがクローズされます。

データを追加
util_db.py(抜粋)
# CRUD(Create)
def insert_record(self, name, comment, score):
    """ データを追加する """
    print("insert_record:", name, comment)
    # Record
    record = Record(
        name=name, 
        comment=comment, 
        score=score, 
        time_stamp=self.get_time())
    with self.db_session() as session:
        session.add(record)
        session.commit()
        return record.uid

5-2, データの取得(Read)

"read_records()"メソッドでは、スコアの降順に、上位"limit"件数だけデータを取得します。

データの取得(降順にlimit件)
util_db.py(抜粋)
# CRUD(Read)
def read_records(self, limit=10):
    """ データを読み込む(limit件数まで) """
    print("read_records:", limit)
    with self.db_session() as session:
        stmt = select(Record).order_by(Record.score.desc()).limit(limit)
        return session.scalars(stmt).all()

"read_record()"メソッドでは、データを1件取得します。
下記の通り、"session.get(Record, uid)"で、"uid"に該当するデータを1件取得しています。

データの取得(1件)
util_db.py(抜粋)
def read_record(self, uid):
    """ データを読み込む(1件) """
    print("read_record:", uid)
    with self.db_session() as session:
        return session.get(Record, uid)

5-3, データの更新(Update)

"update_record()"メソッドでは、テーブルのデータを更新します。

先ほどの、"session.get(Record, uid)"でデータを取得し、
オブジェクトのデータを直接更新します。(とてもシンプルですね)
更新後は、"commit()"を行います。

データの更新
util_db.py(抜粋)
# CRUD(Update)
def update_record(self, uid, name, comment, score):
    """ データを更新する(1件) """
    print("update_record:", uid)
    with self.db_session() as session:
        record = session.get(Record, uid)
        if record is None: return -1
        record.name = name
        record.comment = comment
        record.score = score
        record.time_stamp = self.get_time()
        session.commit()
        return record.uid

5-4, データの削除(Delete)

"delete_record()"メソッドでは、テーブルのデータを削除します。

"session.delete(record)"で削除します。
こちらも、削除後に"commit()"を行います。

データの削除
util_db.py(抜粋)
# CRUD(Delete)
def delete_record(self, uid):
    """ データを削除する(1件) """
    print("delete_record:", uid)
    with self.db_session() as session:
        record = session.get(Record, uid)
        if record is None: return -1
        session.delete(record)
        session.commit()
        return record.uid

テストをする

テスト方法は次のとおりです。
ここでは、ランダムに名前とコメント、スコアを決め、
そのままテーブルに追加しています。
(コメント部分を外すと、更新、削除をテストすることができます)

テスト方法
main.py
# Member
names = ["Alex", "Becky", "Christy", "David"]
comments = ["Champion!!", "Nice!!", "Good!!", "OMG...!!"]

# MyDB
my_db = util_db.MyDB("data.sqlite")

# Create(テーブルを作成する)
my_db.create_table()

# Insert(ランダムに1件追加する)
name = random.choice(names)
comment = random.choice(comments)
score = random.randint(30, 300)
result = my_db.insert_record(name, comment, score)
print("insert:", result)

# Update(ハッカーが現れいたずらする)
#my_db.update_record(1, "Thomas", "Hi, I'm hacker!!", 777)

# Delete(uidが4のデータを削除する)
#my_db.delete_record(4)

# Read(uidが1のデータを1件取得する)
#record = my_db.read_record(1)
#print("Record:", record)

# Read(スコアの上位5件を取得する)
records = my_db.read_records(limit=5)
print("= Ranking =")
for record in records:
    print("Record:", record)

実行結果

実行結果は次のとおりです。(ランキング1位にハッカーが!!)

出力
= Ranking =
Record: uid:1, name:Thomas, comment:Hi, I'm hacker!!, score:777, time_stamp:2026/01/10 01:57:14
Record: uid:8, name:Alex, comment:Champion!!, score:291, time_stamp:2026/01/10 00:01:19
Record: uid:33, name:Christy, comment:OMG...!!, score:263, time_stamp:2026/01/10 01:56:35
Record: uid:16, name:Becky, comment:Nice!!, score:256, time_stamp:2026/01/10 00:01:27
Record: uid:18, name:Christy, comment:OMG...!!, score:252, time_stamp:2026/01/10 00:01:29

完成コード

ここまでの機能を実装した完成コードは、次の通りです。

完成コード
util_db.py
import datetime
import os
from sqlalchemy import (
    create_engine,
    Column,
    Integer,
    select,
    String
)
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker

class MyDB():

    def __init__(self, path):
        """ コンストラクタ """
        self.dir_base = os.path.dirname(__file__)
        self.db_path = "sqlite:///" + os.path.join(self.dir_base, path)
        # Engine, Session
        self.db_engine = create_engine(self.db_path, echo=True)
        self.db_session = sessionmaker(bind=self.db_engine)
        Base.metadata.create_all(self.db_engine) # テーブルを作る

    # CRUD(Create)
    def insert_record(self, name, comment, score):
        """ データを追加する """
        print("insert_record:", name, comment)
        # Record
        record = Record(
            name=name, 
            comment=comment, 
            score=score, 
            time_stamp=self.get_time())
        with self.db_session() as session:
            session.add(record)
            session.commit()
            return record.uid

    # CRUD(Read)
    def read_records(self, limit=10):
        """ データを読み込む(limit件数まで) """
        print("read_records:", limit)
        with self.db_session() as session:
            stmt = select(Record).order_by(Record.score.desc()).limit(limit)
            return session.scalars(stmt).all()

    def read_record(self, uid):
        """ データを読み込む(1件) """
        print("read_record:", uid)
        with self.db_session() as session:
            return session.get(Record, uid)

    # CRUD(Update)
    def update_record(self, uid, name, comment, score):
        """ データを更新する(1件) """
        print("update_record:", uid)
        with self.db_session() as session:
            record = session.get(Record, uid)
            if record is None: return -1
            record.name = name
            record.comment = comment
            record.score = score
            record.time_stamp = self.get_time()
            session.commit()
            return record.uid

    # CRUD(Delete)
    def delete_record(self, uid):
        """ データを削除する(1件) """
        print("delete_record:", uid)
        with self.db_session() as session:
            record = session.get(Record, uid)
            if record is None: return -1
            session.delete(record)
            session.commit()
            return record.uid

    # Time
    def get_time(self):
        """ 現在日時を取得する """
        return datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")

# ORM
Base = declarative_base()
class Record(Base):

    # Table
    __tablename__ = "ranking"
    # ID
    uid = Column(Integer, primary_key=True, autoincrement=True)
    # Name
    name = Column(String(12), nullable=False)
    # Comment
    comment = Column(String(24), nullable=False)
    # Score
    score = Column(Integer, nullable=False)
    # Timestamp
    time_stamp = Column(String(24), nullable=False)

    def __str__(self):
        return "uid:{0}, name:{1}, comment:{2}, score:{3}, time_stamp:{4}".format(
            self.uid, self.name, self.comment, self.score, self.time_stamp)
main.py
import random
import util_db

def main():

    # Member
    names = ["Alex", "Becky", "Christy", "David"]
    comments = ["Champion!!", "Nice!!", "Good!!", "OMG...!!"]
    
    # MyDB
    my_db = util_db.MyDB("data.sqlite")

    # Insert(ランダムに1件追加する)
    name = random.choice(names)
    comment = random.choice(comments)
    score = random.randint(30, 300)
    result = my_db.insert_record(name, comment, score)
    print("insert:", result)

    # Update(ハッカーが現れいたずらする)
    #my_db.update_record(1, "Thomas", "Hi, I'm hacker!!", 777)

    # Delete(uidが4のデータを削除する)
    #my_db.delete_record(4)

    # Read(uidが1のデータを1件取得する)
    #record = my_db.read_record(1)
    #print("Record:", record)

    # Read(スコアの上位5件を取得する)
    records = my_db.read_records(limit=5)
    print("= Ranking =")
    for record in records:
        print("Record:", record)
    

if __name__ == "__main__":
    main()

終わりに...

ここまで読んでいただきありがとうございました。
"SQLAlchemy"は、シンプルで扱いやすいライブラリなので、押さえておいて損は無いと思います。ޱ(ఠ皿ఠ)ว
(よろしければ👍頂けると大変励みになります!!)

GitHubで編集を提案

Discussion