Jimmy
Jimmy

Reputation: 85

python cursor.execute returning empty

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?

Upvotes: 5

Views: 15729

Answers (1)

Philip Tzou
Philip Tzou

Reputation: 6438

The problems:

  1. As @pvg mentioned, you need to escape your input values when querying database;
  2. If you want to fetch a dictionary-like result, passing dictionary=True when you initialize the cursor;
  3. In your original code, you didn't return the variable json_output;
  4. To fetch only one result, use fetchone instead fetchall;
  5. After cursor.close() got called, you can obtain nothing from that cursor no matter you fetched before or not;
  6. 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()

Upvotes: 1

Related Questions