import cs304dbi as dbi # ========================================================== # The functions that do most of the work. def get_people(conn): '''Returns the name and birthdate of all the entries in the person table, as a list of dictionaries. ''' curs = dbi.dict_cursor(conn) curs.execute('select name,birthdate from person') return curs.fetchall() def people_born_in_month(conn,month): '''Returns the name and birthdate of people born in given month, as a list of dictionaries ''' curs = dbi.dict_cursor(conn) # this uses a prepared query, since the 'month' comes # from an untrustworthy source curs.execute(''' select name,birthdate from person where month(birthdate) = %s''', [month]) return curs.fetchall() def people_born_on_weekday(conn,weekday): '''Returns the name and birthdate of people born on the given day of the week (1-7) as a list of dictionaries ''' curs = dbi.dict_cursor(conn) # this uses a prepared query, since the 'month' comes # from an untrustworthy source curs.execute(''' select name,birthdate from person where dayofweek(birthdate) = %s''', [weekday]) return curs.fetchall() # ========================================================== # This starts the ball rolling, *if* the file is run as a # script, rather than just being imported. if __name__ == '__main__': dbi.cache_cnf() # defaults to ~/.my.cnf dbi.use('wmdb') conn = dbi.connect() pl = get_people(conn) for person in pl: print('{name} born on {date}' .format(name=person['name'], date=person['birthdate'])) print('September People') pl = people_born_in_month(conn,9) for person in pl: print('{name} born on {date}' .format(name=person['name'], date=person['birthdate']))