简体   繁体   中英

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM