I have a problem with my python code which I want to use for a REST API server.
The current problem is that my database query is returning null when I know that the value is there
The code for the specific path:
@app.route('/data/active_predicted/<int:ticketId>', methods=['GET'])
def search_db_tickId_act(ticketId):
cursor = db.cursor()
db_query = cursor.execute("select * from active_predicted where ticketId=" + str(ticketId))
json_output = json.dumps(dict(cursor.fetchall()))
cursor.close()
if not cursor.fetchall():
return "Nothing found \n SQL Query: " + "select * from active_predicted where ticketId=" + str(ticketId)
else:
return str(cursor.fetchall())
When I access this URL I get returned the following:
Nothing found SQL Query: select * from active_predicted where ticketId=1324
When I plug this SQL query I get the result I want, 1 row with 2 columns but it seems as though the program cannot locate the row?
1 Answer 1
The problems:
- As @pvg mentioned, you need to escape your input values when querying database;
- If you want to fetch a dictionary-like result, passing
dictionary=Truewhen you initialize the cursor; - In your original code, you didn't return the variable
json_output; - To fetch only one result, use
fetchoneinsteadfetchall; - After
cursor.close()got called, you can obtain nothing from that cursor no matter you fetched before or not; - Use try-finally to ensure that cursor always get closed (at last).
Here's the fixed code:
@app.route('/data/active_predicted/<int:ticketId>', methods=['GET'])
def search_db_tickId_act(ticketId):
try:
cursor = db.cursor(dictionary=True)
db_query = cursor.execute("select * from active_predicted where ticketId=%s LIMIT 1", ticketId)
row = cursor.fetchone()
if row:
return json.dumps(row)
else:
return "Nothing found \n SQL Query: " + "select * from active_predicted where ticketId=" + str(ticketId)
finally:
cursor.close()
answered Jan 5, 2017 at 1:23
Philip Tzou
6,5582 gold badges22 silver badges31 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Jimmy
Thanks! This solution works for me. I had to change some values due to errors but the code mostly stayed the same. Can you tell me what is different from this code and my original as well as why my original code would not work? Thank you very much once again!
Philip Tzou
@Jimmy: glad you solved that. I added the explanation to my answer.
lang-py
json_output = json.dumps(dict(cursor.fetchall())), but I'm not a Python DB expert. I'd also suggest you probably don't want to be using string manipulation for constructing your query (the DB interface has its own safer way of specifying arguments).fetchallreturns a list and I don't think you can pass that result todict(). What is the ideal result you expected?