使用 Python 和 mySQL(以及 windows 作为 OS),cursor.execute() 没有返回任何结果,但它正在连接

Using Python and mySQL (and windows as OS), cursor.execute() is returning no results but it is connecting

所以我遇到的问题与 this question 非常相似,但又有些不同。

我在一块 sql 上调用 cursor.execute(sqlString),当我直接在 mysql workbench 上 运行 它工作正常。但是,当我 运行 代码时,我没有得到任何结果集。

我有与 link 中所述完全相同的问题症状,我已经尝试了 linked 解决方案,但事实证明我没有同样的问题。

返回时我的_stored_results[]为空

我正在使用 try/except 块中的代码,我有另一个 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() 方法之前探测了光标 (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 具有来自过程调用的 return 值

然而,它们不是我应该从 fetchall() 函数中获取它们的良好格式,所以我必须进行一些处理,我必须确保我得到了一些值,我注意到这些值 return 编入元组

我在两台不同的机器上遇到过这个问题 运行 两个不同的 OS 和两个不同版本的 python (Windows 7 和 Python 2.7 和 Windows 10 与 Python 3) 两段代码是不同的所以很明显事实上我使用了两个不同的 MySQL 库所以修复的实际代码在两者中都略有不同案例,但我现在在这两种情况下都将数据从我的数据库中获取到 Python 中的变量中,这很酷。

但是,这是一个 hack,我知道这一点,我宁愿使用正确的函数 cur.fetchall() 所以我仍然愿意接受有关这里可能出现问题的建议。