0% found this document useful (0 votes)
86 views2 pages

Week 4 Code For Jupyter

This Python script connects to a SQLite database called rosterdb.sqlite and creates tables to store user, course, and member data from a JSON file. It then iterates through the JSON data, inserts or updates the user, course, and member records in the database tables, and commits the changes. Finally, it performs a join query on the tables and prints the result.

Uploaded by

Parveen Mittal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views2 pages

Week 4 Code For Jupyter

This Python script connects to a SQLite database called rosterdb.sqlite and creates tables to store user, course, and member data from a JSON file. It then iterates through the JSON data, inserts or updates the user, course, and member records in the database tables, and commits the changes. Finally, it performs a join query on the tables and prints the result.

Uploaded by

Parveen Mittal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import json

import sqlite3

conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()

# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;

CREATE TABLE User (


id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);

CREATE TABLE Course (


id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);

CREATE TABLE Member (


user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')

fname = "roster_data.json"
if len(fname) < 1:
fname = 'roster_data_sample.json'

# [
# [ "Charley", "si110", 1 ],
# [ "Mea", "si110", 0 ],

str_data = open(fname).read()
json_data = json.loads(str_data)

for entry in json_data:

name = entry[0];
title = entry[1];
role=entry[2];

# print((name, title,role))

cur.execute('''INSERT OR IGNORE INTO User (name)


VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]

cur.execute('''INSERT OR IGNORE INTO Course (title)


VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id,role) VALUES ( ?, ?, ? )''',
( user_id, course_id,role ) )

conn.commit()

test="""SELECT hex(User.name || Course.title || Member.role ) AS X FROM


User JOIN Member JOIN Course
ON User.id = Member.user_id AND Member.course_id = Course.id
ORDER BY X"""
cur.execute(test)
result=cur.fetchone()
print(result)
cur.close()
conn.close()

You might also like