python cursor.execute返回空

时间:2017-01-05 00:50:26

标签: python mysql-python

我的python代码存在问题,我想将其用于REST API服务器。

当前的问题是,当我知道值为

时,我的数据库查询返回null

特定路径的代码:

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

当我访问此网址时,我会收到以下内容:

没有找到SQL Query:select * from active_predicted where ticketId = 1324

当我插入这个SQL查询时,我得到了我想要的结果,1行有2列,但似乎程序无法找到该行?

1 个答案:

答案 0 :(得分:0)

问题:

  1. 正如@pvg所提到的,在查询数据库时需要转义输入值;
  2. 如果要获取类似字典的结果,请在初始化光标时传递dictionary=True;
  3. 在原始代码中,您没有返回变量json_output;
  4. 要仅提取一个结果,请使用fetchone代替fetchall;
  5. 调用cursor.close()之后,无论您之前是否取得任何内容,都无法从该游标中获取任何内容;
  6. 使用try-finally确保光标始终关闭(最后)。
  7. 这里是固定代码:

    @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()
    
相关问题