1+ # This application will read roster data in JSON format, parse the file, and
2+ # then produce an SQLite database that contains a User, Course, and Member table
3+ # and populate the tables from the data file.
4+ # This is Many-to-Many relationship between User and Course, a junction table of Member was
5+ # created to form a pair of one-to-many relationships.
6+ # The date used was in roster_data.json file. The results was stored in rosterdb.sqlite file.
7+
8+ import json
9+ import sqlite3
10+
11+ conn = sqlite3 .connect ('rosterdb.sqlite' )
12+ cur = conn .cursor ()
13+
14+ # executescript(): execute multiply SQL statement with one call
15+ cur .executescript ('''
16+ DROP TABLE IF EXISTS User;
17+ DROP TABLE IF EXISTS Member;
18+ DROP TABLE IF EXISTS Course;
19+
20+ CREATE TABLE User (
21+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
22+ name TEXT UNIQUE
23+ );
24+
25+ CREATE TABLE Course (
26+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
27+ title TEXT UNIQUE
28+ );
29+
30+ CREATE TABLE Member (
31+ user_id INTEGER,
32+ course_id INTEGER,
33+ role INTEGER,
34+ PRIMARY KEY (user_id, course_id)
35+ )
36+ ''' )
37+
38+ fname = raw_input ('Enter file name: ' )
39+ if ( len (fname ) < 1 ) : fname = 'roster_data.json'
40+
41+ # [
42+ # [ "Charley", "si110", 1 ],
43+ # [ "Mea", "si110", 0 ],
44+
45+ str_data = open (fname ).read ()
46+ json_data = json .loads (str_data )
47+
48+ for entry in json_data :
49+
50+ name = entry [0 ];
51+ title = entry [1 ];
52+ role = entry [2 ];
53+
54+ print name , title , role
55+
56+ cur .execute ('''INSERT OR IGNORE INTO User (name)
57+ VALUES ( ? )''' , ( name , ) )
58+ cur .execute ('SELECT id FROM User WHERE name = ? ' , (name , ))
59+ user_id = cur .fetchone ()[0 ]
60+
61+ cur .execute ('''INSERT OR IGNORE INTO Course (title)
62+ VALUES ( ? )''' , ( title , ) )
63+ cur .execute ('SELECT id FROM Course WHERE title = ? ' , (title , ))
64+ course_id = cur .fetchone ()[0 ]
65+
66+ cur .execute ('''INSERT OR REPLACE INTO Member
67+ (user_id, course_id, role) VALUES ( ?, ?, ? )''' ,
68+ ( user_id , course_id , role ) )
69+
70+ conn .commit ()
0 commit comments