-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase2-crud.py
59 lines (45 loc) · 1.62 KB
/
database2-crud.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
48
49
50
51
52
53
54
55
56
57
58
59
# creating, retrieving, updating and deleting records, CRUD
# when you make changes to the database, you must call .commit()
#!/usr/bin/python3
# sqlite3-crud.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
import sqlite3
def insert(db, row):
db.execute('insert into test (t1, i1) values (?, ?)', (row['t1'], row['i1']))
db.commit()
def retrieve(db, t1):
cursor = db.execute('select * from test where t1 = ?', (t1,))
return cursor.fetchone()
def update(db, row):
db.execute('update test set i1 = ? where t1 = ?', (row['i1'], row['t1']))
db.commit()
def delete(db, t1):
db.execute('delete from test where t1 = ?', (t1,))
db.commit()
def disp_rows(db):
cursor = db.execute('select * from test order by t1')
for row in cursor:
print(' {}: {}'.format(row['t1'], row['i1']))
def main():
db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row
print('Create table test')
db.execute('drop table if exists test')
db.execute('create table test ( t1 text, i1 int )')
print('Create rows')
insert(db, dict(t1 = 'one', i1 = 1))
insert(db, dict(t1 = 'two', i1 = 2))
insert(db, dict(t1 = 'three', i1 = 3))
insert(db, dict(t1 = 'four', i1 = 4))
disp_rows(db)
print('Retrieve rows')
print(dict(retrieve(db, 'one')), dict(retrieve(db, 'two')))
print('Update rows')
update(db, dict(t1 = 'one', i1 = 101))
update(db, dict(t1 = 'three', i1 = 103))
disp_rows(db)
print('Delete rows')
delete(db, 'one')
delete(db, 'three')
disp_rows(db)
if __name__ == "__main__": main()