-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
133 lines (97 loc) · 2.49 KB
/
database.py
File metadata and controls
133 lines (97 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# database.py
import sqlite3
DB_NAME = "task.db"
# DB接続
def connect_db():
conn = sqlite3.connect(DB_NAME)
conn.row_factory = sqlite3.Row
return conn
# テーブル作成
def create_tables():
conn = connect_db()
cur = conn.cursor()
# 【重要】外部キー制約を有効にする
cur.execute("PRAGMA foreign_keys = ON;")
# usersテーブル
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
""")
# tasksテーブル
cur.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
category TEXT NOT NULL,
task_time TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
)
""")
conn.commit()
conn.close()
# ユーザー登録
def register_user(name, password):
conn = connect_db()
cur = conn.cursor()
cur.execute(
"INSERT INTO users (name, password) VALUES (?, ?)",
(name, password)
)
conn.commit()
conn.close()
# ログイン確認
def login_user(name, password):
conn = connect_db()
cur = conn.cursor()
cur.execute(
"SELECT * FROM users WHERE name=? AND password=?",
(name, password)
)
user = cur.fetchone()
conn.close()
return user
# 主なCRUD機能
# タスク追加
def Create(user_id, title, category, task_time):
conn = connect_db()
cur = conn.cursor()
cur.execute(
"INSERT INTO tasks (user_id, title, category, task_time) VALUES (?, ?, ?, ?)",
(user_id, title, category, task_time)
)
conn.commit()
conn.close()
# タスク取得
def Read(user_id):
conn = connect_db()
cur = conn.cursor()
cur.execute(
"SELECT * FROM tasks WHERE user_id=? ORDER BY task_time ASC",
(user_id,)
)
tasks = cur.fetchall()
conn.close()
return tasks
# 更新
def Update(task_id, user_id, new_title):
conn = connect_db()
cur = conn.cursor()
cur.execute(
"UPDATE tasks SET title = ? WHERE id = ? AND user_id = ?",
(new_title, task_id, user_id)
)
conn.commit()
conn.close()
# 削除
def Delete(task_id, user_id):
conn = connect_db()
cur = conn.cursor()
cur.execute("DELETE FROM tasks WHERE id = ? AND user_id = ?",
(task_id, user_id)
)
conn.commit()
conn.close()