-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathsqlite1.py
More file actions
96 lines (83 loc) · 2.29 KB
/
Copy pathsqlite1.py
File metadata and controls
96 lines (83 loc) · 2.29 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
"""
Example SQLite usage using PySQLite Connector/Python
https://www.sqlitetutorial.net/sqlite-python/
"""
import sqlite3
from sqlite3 import Error
def drop_table(conn):
"""Drop table."""
cur = conn.cursor()
try:
sql = "DROP TABLE postcodes"
cur.execute(sql)
except Error as err:
# if err.errno == errorcode.ER_BAD_TABLE_ERROR:
# print("Error: Table does not exist.")
# else:
print("Error: {}".format(err))
else:
print("Table dropped.")
finally:
cur.close()
def create_table(conn):
"""Create table."""
cur = conn.cursor()
try:
sql = ("CREATE TABLE postcodes ("
"postcode text, "
"location text, "
"PRIMARY KEY(postcode))")
cur.execute(sql)
except Error as err:
print("Error: {}".format(err))
else:
print("Table created.")
finally:
cur.close()
def insert_data(conn):
"""Insert data to a table."""
postcodes = {
"0001": "Oslo",
"4036": "Stavanger",
"4041": "Hafrsfjord",
"7491": "Trondheim",
"9019": "Tromsø"
}
cur = conn.cursor()
num = 0
for k, v in postcodes.items():
sql = "INSERT INTO postcodes (postcode, location) VALUES (?, ?)"
try:
cur.execute(sql, (k, v)) # data is provided as a tuple
conn.commit() # commit after each row
except Error as err:
print("Error: {}".format(err))
else:
num += 1
print("{:d} rows inserted.".format(num))
cur.close()
def query_data(conn):
"""Querying data."""
cur = conn.cursor()
try:
sql = ("SELECT postcode, location FROM postcodes "
"WHERE postcode BETWEEN ? AND ?")
cur.execute(sql, ("4000","5050"))
print(cur.fetchall())
# for (postcode, location) in cur:
# print("{}: {}".format(postcode, location))
except Error as err:
print("Error: {}".format(err))
finally:
cur.close()
if __name__ == "__main__":
try:
conn = sqlite3.connect("database_file.db")
except Error as err:
print(err)
else:
#drop_table(conn)
create_table(conn)
insert_data(conn)
query_data(conn)
conn.close()