mercredi 2 septembre 2015

Passing parameters in SQLite in Python/Flask

I have a very dumb issue which I've been absolutely breaking my head over for a while now

##########CODE 1 (STATIC)##############
@app.route('/fromdb', methods=['GET'])
def printall():

data = g.db.execute("SELECT TeacherInfo.Name, TeacherInfo.PhoneNo, TeacherInfo.HourlyRate, SubjectTable.SubjectName, SubjectTable.Grade, SubjectTable.Syllabus FROM SubjectTable JOIN TeacherInfo on SubjectTable.TeacherID = TeacherInfo.TeacherID WHERE SubjectName = 'Comp'").fetchall()
   print(data)
   return jsonify(details=data)
##########END CODE1###################


##########CODE 2(DYNAMIC)#############
@app.route('/fromdb', methods=['GET'])
def printall():

   x = request.json

   p = x['SubjectName']

   data = g.db.execute("SELECT TeacherInfo.Name, TeacherInfo.PhoneNo, TeacherInfo.HourlyRate, SubjectTable.SubjectName, SubjectTable.Grade, SubjectTable.Syllabus FROM SubjectTable JOIN TeacherInfo on SubjectTable.TeacherID = TeacherInfo.TeacherID WHERE SubjectName = ?", p).fetchall()
   print(data)
   return jsonify(details=data)
##########END CODE2###################

In the link above, there are two codes Code 1 works perfectly fine, I'm focusing on the 'WHERE SubjectName = 'Comp'' and WHERE SubjectName = ? here

I hard code the subject name into the query, and I get a JSON object with the results of the query

Now, in code 2, the variable 'p' contains the subject name and I'm able to retrieve it and print it. But the query isn't working, I'm getting a 500 error and I'm not sure how I pass it as a parameter in the query.

Could someone please help me out with this?

Aucun commentaire:

Enregistrer un commentaire