gpt4 book ai didi

python - 无法使用 Python 游标从存储过程返回结果

转载 作者:IT王子 更新时间:2023-10-29 00:33:16 27 4
gpt4 key购买 nike

由于某种奇怪的原因,我无法从 Python 测试应用程序中的 callproc 调用中获得结果。 MqSQL 5.2.47 中的存储过程如下所示:

CREATE PROCEDURE `mytestdb`.`getperson` (IN personid INT)
BEGIN
select person.person_id,
person.person_fname,
person.person_mi,
person.person_lname,
person.persongender_id,
person.personjob_id
from person
where person.person_id = personid;
END

现在,在 Python 3.3 中使用 PyCharm,调用此存储过程时我似乎无法检索任何内容。这段代码让我得到了想要的结果:

import mysql.connector

cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='mytestdb')
cnx._open_connection()
cursor = cnx.cursor()

cursor.execute("select * from person where person.person_id = 1")
people = cursor.fetchall()

for person in people:
print(person)

cnx.close()

但是这段代码使用 cursor.fetchall() 或 cursor.fetchone()...

import mysql.connector

cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='mytestdb')
cnx._open_connection()
cursor = cnx.cursor()

cursor.callproc("getperson", [1])
people = cursor.fetchall()

for person in people:
print(person)

cnx.close()

...返回“mysql.connector.errors.InterfaceError:没有要从中获取的结果集。”像这样使用 cursor.execute() 方法还有一个奇怪的行为......

import mysql.connector

cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='mytestdb')
cnx._open_connection()
cursor = cnx.cursor()

cursor.execute("call getperson(1)")
people = cursor.fetchall()

for person in people:
print(person)

cnx.close()

...因为它产生“mysql.connector.errors.InterfaceError: Use cmd_query_iter for statements with multiple queries”后跟“mysql.connector.errors.InterfaceError: Use multi=True when execution multiple statements”尽管事实上我只返回一个查询结果而不是多个结果集。 MySQL Python 连接器是否将存储过程上的执行调用视为双重查询?我怎样才能调用存储过程并取回我的结果?我真的不想在我的代码中使用动态 SQL。提前感谢您的任何建议!

最佳答案

您是否尝试过选择其中一个结果集?

for result in cursor.stored_results():
people = result.fetchall()

即使您只有一个 SELECT stmt,它也可能分配给多个结果集。我知道在 PHP 的 MySQLi 存储过程中这样做是为了允许 INOUT 和 OUT 变量返回(同样,你没有,但也许它无论如何都在分配)。

我正在使用的完整代码(正在运行)是:

import mysql.connector

cnx = mysql.connector.connect(user='me',password='pw',host='localhost',database='mydb')
cnx._open_connection()
cursor = cnx.cursor()

cursor.callproc("getperson",[1])

for result in cursor.stored_results():
people=result.fetchall()

for person in people:
print person

cnx.close()

关于python - 无法使用 Python 游标从存储过程返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15320265/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com