COMP3311 Final Exam 21T3 The University of New South Wales
COMP3311 Database Systems
Final Exam 21T3
Database Systems
[Front Page] [Notes] [Database] [Course Website] [Cheat Sheets]
[Q1] [Q2] [Q3] [Q4] [Q5] [Q6] [Q7] [Q8] [Q9] [Q10]

Question 7 (6 marks)

Consider the following two fragments of Python/Psycopg2 code:

A B
import psycopg2
zid = 5128688
q1 = '''
select t.id,t.code
from   program_enrolments e
       join terms t on e.term = t.id
where  e.student = %s
order by t.starting
'''
q2 = '''
select s.code, s.name
from   course_enrolments e
       join courses c on e.course = c.id
       join subjects s on c.subject = s.id
where  c.term = %s and e.student = %s
order by s.code
'''

try:
   db = psycopg2.connect("dbname=mymyunsw")
   c1 = db.cursor()
   c2 = db.cursor()
   c1.execute(q1,[zid])
   for t in c1.fetchall():
      print(t[1])
      c2.execute(q2,[t[0],zid])
      for s in c2.fetchall():
         print(s[0],s[1])
   c2.close()
   c1.close()
except:
   print("DB error: ", err)
finally:
   if db:
      db.close()
   
import psycopg2
zid = 5128688
q1 = '''
select t.id, t.code, s.code, s.name
from   course_enrolments e
       join courses c on e.course = c.id
       join terms t on c.term = t.id
       join subjects s on c.subject = s.id
where  e.student = %s
order by t.starting,s.code
'''

try:
   db = psycopg2.connect("dbname=mymyunsw")
   c = db.cursor()
   c.execute(q1,[zid])
   prev = 0
   for t in c.fetchall():
      if t[1] != prev:
         print(t[1])
      print(t[2],t[3])
      prev = t[1]
   c.close()
except:
   print("DB error: ", err)
finally:
   if db:
      db.close()

Assume that this student (zid:5128688) studied 29 subjects over 10 terms. Assume also that the scripts have no errors.

  1. Do these two scripts produce the same output?

  2. How many times does each script call the execute() method?

  3. Which script is likely to be faster?

Instructions:

End of Question