2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

標準ライブラリでメモデータベース

Last updated at Posted at 2025-11-27

標準ライブラリだけでデータベースアプリを作ってみた。

作ってみたのはメモを記録閲覧するデータベースアプリです。
テキスト画面(端末画面)にメニュー表示しながら追加、一覧、削除する機能を持っています。

ソース

memo.py
import sqlite3 as sql
import time as tm
import datetime

def getTimeStr():
    """
    現在の日付と時刻を 'YYYYMMDDHHMMSS' 形式の文字列で取得します。
    
    戻り値:
        str: 現在の日付と時刻を表す文字列 (例: "20251127214500")
    """
    # 現在のdatetimeオブジェクトを取得します
    now = datetime.datetime.now()
    # strftime() を使用して指定された形式にフォーマットします
    # %Y: 4桁の西暦, %m: 月, %d: 日, %H: 時 (24時間表記), %M: 分, %S: 秒
    formatted_time = now.strftime('%Y%m%d%H%M%S')
    return formatted_time

dbname = "memo.db"
dcn = sql.connect(dbname)
 
def insNew():
    print("insert start")
    print("titleを未入力にするとinsertを中断します。")
    title = input("title:")
    memo = ""
    if len(title) > 0:
        print("memoの入力終了は__endと入力")
        imemo = input("memo:")
        while imemo != "__end":
            memo += imemo+"\n"
            if imemo != "":
                imemo = input("memo:")
        ctime = getTimeStr()
        utime = ctime
        cur = dcn.cursor()
        cur.execute("INSERT INTO memo_tbl (title,memo,ctime,utime) VALUES (?,?,?,?)",(title,memo,ctime,utime))
        dcn.commit()
    return True

def listData():
    pg=10
    cur = dcn.cursor()
    res = cur.execute("SELECT COUNT(id) FROM memo_tbl;")
    fd = res.fetchone()
    page = 1
    dmax = fd[0]
    print(f"dmax={dmax} page={page}")
    if dmax == 0:
        print("データはありません。")
        return
    pmax = dmax//pg+1
    #
    offset = (page-1)*pg
    limit = pg
    loopf=True
    while loopf:
        res = cur.execute(f"SELECT id,title FROM memo_tbl LIMIT {limit} OFFSET {offset};")
        for rec in res:
            print(f"{rec[0]}:{rec[1]}")
        print("表示終了はeと入力")
        num = input("表示レコード番号:")
        if num == "n":
            page += 1
            if pmax < page:
                print("次のページはありません。")
            else:
                offset = (page-1)*pg
                limit = pg
        elif num == "e":
            loopf = False
        else:
            res = cur.execute(f"SELECT title,utime,memo FROM memo_tbl WHERE id={num};")
            rec = res.fetchone()
            if rec == None:
                return 
            print(f"----- TITLE:{rec[0]} ----- TIME:{rec[1]} -----")
            print(rec[2])
            cmd = input("削除する場合はdと入力:")
            if cmd=="d":
                cur.execute(f"DELETE FROM memo_tbl WHERE id={num};")
                dcn.commit()
                dmax -= 1
                if dmax == 0:
                    print("データはありません。")
                    loopf = False
                    return

def menu():
    menus=["1.new record","2.data list","e:end"]
    def prmenu():
        for m in menus:
            print(m)
        cmd=input("CMD:")
        if cmd=='e':
            return False
        if cmd=='1':
            insNew()
        if cmd=='2':
            listData()
        return True
    cont = True
    while cont:
        try:
            cont = prmenu()
        except Exception as e:
            print(f'caught {type(e)}: e')

menu()
dcn.close()

テーブル仕様

memo_tbl.sql
CREATE TABLE "memo_tbl" (
	"id"	INTEGER,
	"title"	TEXT NOT NULL,
	"memo"	TEXT,
	"ctime"	TEXT NOT NULL,
	"utime"	TEXT NOT NULL,
	PRIMARY KEY("id" AUTOINCREMENT)
)

このテーブルを含むmemo.dbをsqlite3またはsqlitebrowserコマンドで作ります。

ダウンロードはこちら
ソースとデータベースファイルが入っています。
Windowsユーザーの方はWSLで使ってくださいね。
tar xovfz memodb.tgz
で解凍できます。

どんな感じで動くのか?

どんな感じで動くのかは、以下の動画を参考にしてください!!
https://youtu.be/wLuFXb52DoU

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?