python cursor.execute返回空
我想用于RESTAPI服务器的python代码有问题 当前的问题是,当我知道该值存在时,我的数据库查询返回null 特定路径的代码:python cursor.execute返回空,python,mysql-python,Python,Mysql Python,我想用于RESTAPI服务器的python代码有问题 当前的问题是,当我知道该值存在时,我的数据库查询返回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 ac
@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())
@app.route('/data/active_predicted/',methods=['GET']))
def搜索法(TICKTID):
cursor=db.cursor()
db_query=cursor.execute(“从活动中选择*”,其中ticketId=“+str(ticketId))
json_output=json.dumps(dict(cursor.fetchall()))
cursor.close()
如果不是游标,则为cursor.fetchall():
返回“未找到任何内容”\n SQL查询:“+”从活动中选择*,其中ticketId=“+str(ticketId)
其他:
返回str(cursor.fetchall())
当我访问此URL时,返回以下信息:
未找到任何内容SQL查询:从活动中选择*,其中ticketId=1324
当我插入此SQL查询时,我得到了我想要的结果,1行2列,但程序似乎找不到该行?问题:
dictionary=True
李>
json_output
李>
fetchone
而不是fetchall
李>
cursor.close()
后,无论之前是否获取,都无法从该游标获取任何内容李>
@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()
@app.route('/data/active_predicted/',methods=['GET']))
def搜索法(TICKTID):
尝试:
cursor=db.cursor(dictionary=True)
db_query=cursor.execute(“从活动_中选择*,其中ticketId=%s LIMIT 1”,ticketId)
row=cursor.fetchone()
如果行:
返回json.dumps(行)
其他:
返回“未找到任何内容”\n SQL查询:“+”从活动中选择*,其中ticketId=“+str(ticketId)
最后:
cursor.close()
我猜您正在使用行json\u output=json.dumps(dict(cursor.fetchall())
中的所有结果,但我不是Python DB专家。我还建议您可能不想在构造查询时使用字符串操作(DB接口有自己更安全的指定参数的方法)。首先,不要通过字符串连接构造查询,您的程序很容易受到sql注入的攻击。游标的命名也是有原因的——它在结果集中向前移动,因此您不能重复调用“fetchall”——第一个fetchall会获取所有结果。@pvg谢谢您提供的提示,我已经习惯了java编程,所以对于函数我不是很确定。另外,感谢您提供有关SQL注入的提示。问题是,即使没有底部的if-else语句,返回的JSON对象中仍然没有任何数据。fetchall
返回一个列表,我认为您无法将该结果传递给dict()
。您期望的理想结果是什么?@Jimmy np,您可能想了解python db api(无论您使用什么驱动程序来实现它)。游标和预处理语句的基本概念与JDBC非常相似,谢谢!这个解决方案对我有效。由于出现错误,我不得不更改一些值,但代码基本保持不变。你能告诉我这个代码和我的原始代码有什么不同,以及为什么我的原始代码不能工作吗?再次非常感谢@吉米:很高兴你解决了这个问题。我在回答中加上了解释。