我正在尝试在多数据库 Django 安装上调用存储过程,但没有获得结果。存储过程(位于辅助数据库上)在 Django 中始终返回一个空数组,但在 mysql 客户端中执行时确实会出现预期结果。
我的view.py文件 从 SomeDBModel 导入模型 从 django.db 导入连接
def index(request, someid):
#Some related django-style query that works here
loc = getLocationPath(someid, 1)
print(loc)
def getLocationPath(id, someval):
cursor = connection.cursor()
cursor.callproc("SomeDB.spGetLocationPath", [id, someval])
results = cursor.fetchall()
cursor.close()
return results
我也尝试过:
from SomeDBModel import models
from django.db import connections
def index(request, someid):
#Some related Django-style query that works here
loc = getLocationPath(someid, 1)
print(loc)
def getLocationPath(id, someval):
cursor = connections["SomeDB"].cursor()
cursor.callproc("spGetLocationPath", [id, someval])
results = cursor.fetchall()
cursor.close()
return results
每次打印结果时,我都会得到:
[]
应检索的数据示例:
{
Path: '/some/path/',
LocalPath: 'S:\Some\local\Path',
Folder: 'SomeFolderName',
Code: 'SomeCode'
}
我还尝试过的一件事是打印 cursor.callproc 的结果。我得到:
(id, someval)
此外,打印 cursor._execulated 的结果给出:
b'SELECT @_SomeDB.spGetLocationPath_arg1, @_SomeDB.spGetLocationPath_arg2'
这似乎根本没有任何对我想要运行的存储过程的引用。我什至尝试过将此作为最后的手段:
cursor.execute("CALL spGetLocationPath("+str(id)+","+str(someval)+")")
但是我收到一个关于需要multi=True的错误,但是将其放入execute()函数中似乎并不像某些网站建议的那样工作,而且我不知道还有什么地方将其放入 Django 中。
那么...我错过了什么想法吗?如何使存储过程正常工作?
最佳答案
这些是我采取的以下步骤:
- 使我的存储过程将结果转储到临时表中,以便将结果集展平为单个结果集。这消除了对
multi=True
的需要
- 此外,我还确保使用我的 IP 地址的用户有权调用数据库本身中的存储过程。
最后,我继续研究callproc函数。最终,另一个网站上的某人建议了以下代码,该代码有效:
cur = connections["SomeDB"].cursor() cur.callproc("spGetLocationPath", [id, someval]) res = next(cur.stored_results()).fetchall() cur.close()
关于mysql - Django 在第二个数据库上调用存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27946350/