-
Notifications
You must be signed in to change notification settings - Fork 0
/
00_sqlite3_driver.py
78 lines (61 loc) · 2.62 KB
/
00_sqlite3_driver.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
################ Video-Tutorials ################
# https://www.youtube.com/watch?v=Ohj-CqALrwk&list=PLXoQruUZzEmHEq9462MgL3mPLeQ0VULeQ&index=5&t=500s
# https://www.youtube.com/watch?v=MkGQmZoMuRM&list=PLXoQruUZzEmHEq9462MgL3mPLeQ0VULeQ&index=5&ab_channel=PythonSimplified
################ Read-Tutorials ################
# https://sqlite.org/cli.html
################ CLI: sqlite3 test.db ################
# create table persons(id integer primary key autoincrement, name text);
# .tables # display all tables
# .schema persons # display schema of table
# .help # show help
## csv export:
# .mode csv # set output mode
# .headers on # display column headers
# .output FILE # send output to file
# Select * from person # select rows for output
## csv import:
# .mode csv # set output mode
# .headers on # display column headers
# .import FILE TABLE --skip 1 # import rows from csv into table (skip 1 header row in csv)
# sqlite3 lib is by default included
import sqlite3
# create a connection
# transaction is started by default:
con = sqlite3.connect("test.db")
# Most DBAPIs have a transaction ongoing which is auto-begin() on connect()
# which will begin a transaction implicitly
# create a cursor for executing sql stmts:
cursor = con.cursor()
# create table:
cursor.execute("Create table if not exists person(id integer primary key autoincrement, name text, age integer)")
# Delete rows:
cursor.execute("Delete from person")
con.commit()
print("****** Insert Rows *****************")
# Insert rows: Tuple Placeholder Style with "?"
person_data = [("Max", 66), ("Sam", 24), ("Jerome", 33)]
cursor.executemany("Insert into person(name, age) values (?,?)", person_data)
print("****** Select *********************")
# Read data:
cursor.execute("Select * from person where age > 30")
results = cursor.fetchall()
for id, name, age in results:
print(f"({id}) Name: {name} is {age} years old.")
print("****** update **************************")
# update data: Named Placeholder Style with :key
cursor.execute("update person set age=:age, name=:new_name where name=:old_name",
{"old_name": "Max", "age": 19, "new_name": "Maxine"})
cursor.execute("Select * from person")
results = cursor.fetchall()
print("******** select **************************")
for id, name, age in results:
print(f"({id}) Name: {name} is {age} years old.")
# commit transaction:
con.commit()
# DBAPIs doesnt know of any con.begin()
# because transaction is begun by default
# on con.connect()
# But every DBAPI has:
# con.commit() + con.rollback()
con.rollback()
con.close()