-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctrl_sqlite.py
47 lines (37 loc) · 1.19 KB
/
ctrl_sqlite.py
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
import sqlite3
from contextlib import closing
dbname = 'name.db'
def main():
global dbname
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
create_table = 'create table users(id varchar(16) primary key, name varchar(64))'
c.execute(create_table)
def search(user_id):
global dbname
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
search_user = 'select name from users where id=?'
u_id = (user_id,)
c.execute(search_user, u_id)
res = c.fetchone()
#返り値はNoneかタプル res[0]に名前が入ってる
return res
def insert(user_id, name):
global dbname
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
insert_sql = 'insert into users values (?, ?)'
u_id = (user_id, name)
c.execute(insert_sql, u_id)
conn.commit()
def update(user_id, name):
global dbname
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
update_sql = 'update users set name=? where id=?'
u_id = (name, user_id)
c.execute(update_sql, u_id)
conn.commit()
if __name__ == '__main__':
main()