-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsqlite_example.py
More file actions
89 lines (68 loc) · 2.12 KB
/
sqlite_example.py
File metadata and controls
89 lines (68 loc) · 2.12 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
#!/usr/bin/env python
"""
Example of using sqlite3 module for a relational database
"""
import sqlite3, os
db_filename = "add_book_data.sqlite" # any extension will do -- *.db and *.sqlite are common
# get the data from the py file
from add_book_data_flat import AddressBook
# if the db already exists -- delete it:
try:
os.remove(db_filename)
except OSError:
print "no db file there yet"
# create a connection to an sqlite db file:
conn = sqlite3.connect(db_filename)
# NOTE: you can do an in-memory version:
#conn = sqlite3.connect(":memory:")
# establish the schema (single table in this case...):
# Create a table
conn.execute("""CREATE TABLE addresses
( first_name text,
last_name text,
address_line_1 text,
address_line_2 text,
address_city text,
address_state text,
address_zip text,
email text,
home_phone text,
office_phone text,
cell_phone text
)"""
)
conn.commit()
# get the fields from the data:
fields = AddressBook[0].keys()
# order matters, so we sort to make sure they will always be in the same order
fields.sort()
# add some data:
# get a cursor:
c = conn.cursor()
for person in AddressBook:
# Insert a row of data
row = [ person[field] for field in fields ]
row = "','".join(row)
sql = "INSERT INTO addresses VALUES ('%s')"%row
#print sql
c.execute(sql)
# Save (commit) the changes and close the connection
conn.commit()
conn.close()
### see if we can re-load it
conn = sqlite3.connect(db_filename)
sql = "SELECT * FROM addresses"
# no need for a cursor if a single sql statement needs to be run
result = conn.execute(sql)
## put it all back in a list of dicts
AddressBook2 = []
for row in result:
d = dict(zip(fields, row))
AddressBook2.append(d)
if AddressBook2 == AddressBook:
print "the version pulled from sqlite is the same as the original"
else:
print "they don't match!"
conn.close()
## now do it with the non-flat version -- with a proper schema
# left as an exercise for the reader