所以我有一个与 this question 非常相似但又有点不同的问题。
我在一段 sql 上调用 cursor.execute(sqlString)
,当我直接在 mysql 工作台上运行它时,它运行良好。然而,当我运行代码时,我没有得到任何结果集。
我有与链接中所述完全相同的问题症状,我已经尝试了链接的解决方案,但事实证明我没有同样的问题。
返回时我的 _stored_results[] 为空。
我在 try/except block 中使用代码,我有另一个 python 程序使用相同的代码将 csv 加载到我的 mySQL 数据库中并且它工作得很好。
我遇到问题的代码在 @app.route 中,如果有任何不同的话。
我的代码是这样的:
def functionName() :
try:
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect(user=init["dbDetails"][0], password=init["dbDetails"][1], host=init["dbDetails"][2], database=init["dbDetails"][3])
cur = cnx.cursor()
cur.close() #I deffo don't need the two lines below but they were added for a sanity check, just to make sure the cur was not being read from any other code.
cur = cnx.cursor() # and this one obviously
sqlString = 'CALL `schemaName`.`getProcedureName_sp`(1, 1, 0)'
cur.execute(sqlString, multi=True) # tried it here without the multi=True and got the msg telling me to use it.
getSomeDetails = cur.fetchall()
cnx.commit() # probably don't need to commit here I am just reading from the dB but I am trying anything as I have no idea what my issue might be.
return render_template('success.html')
except Exception as e:
return render_template('error.html', error = str(e))
finally:
cur.close()
cnx.close()
我很困惑,因为我在多个地方使用相同的代码。
最佳答案
所以我用这个把头撞在墙上,当我无处可去时,我只是决定离开它继续前进,然后带着新的想法回来。好吧……有点儿奏效了。
所以我还没有找到解决方案,但我找到了一个可以解决问题的解决方案,甚至可以阐明我的代码中实际发生的事情。
我决定,由于 fetchall() 方法是给我带来麻烦的原因,我应该设法绕过它。
我在调用 fetchall() 方法之前探测了 cursor(cur),发现 cur._rows 包含 SQL 调用的结果。
所以我换了行
getSomeDetails = cur.fetchall()
到
if len(cur._rows) > 0 :
getSomeDetails = list(cur._rows[0]) #I only ever expect one result in this query
#getSomeDetails should now have the row I am looking for
getSomeDetails[0] #gets me the field I am looking for
现在我的变量 getSomeDetails 具有过程调用的返回值
然而,它们不是我应该从 fetchall() 函数中获取它们的良好格式,所以我必须进行一些处理,我必须确保我得到了一些值,我注意到这些值是在元组中返回
我在运行两个不同操作系统和两个不同版本的 python(Windows 7 和 Python 2.7 和 Windows 10 和 Python 3)的两台不同机器上遇到过这个问题,这两段代码是不同的,所以很明显事实上我使用了两个不同的MySQL 库,因此修复的实际代码在这两种情况下略有不同,但我现在在这两种情况下都将数据从我的数据库中获取到 Python 中的变量中,这很酷。
但是,这是一个 hack,我知道这一点,我宁愿使用正确的函数 cur.fetchall() 所以我仍然愿意接受有关这里可能出现问题的建议。
关于python - 使用 Python 和 mySQL(和 windows 作为操作系统),cursor.execute() 没有返回任何结果,但它正在连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45638666/