【问题标题】:Django Call Stored Procedure on Second DatabaseDjango 在第二个数据库上调用存储过程
【发布时间】:2015-03-12 20:06:33
【问题描述】:

我正在尝试在多数据库 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._executed 的结果会给出:

b'SELECT @_SomeDB.spGetLocationPath_arg1, @_SomeDB.spGetLocationPath_arg2'

这似乎对我想要运行的存储过程没有任何引用。我什至尝试过这是最后的手段:

cursor.execute("CALL spGetLocationPath("+str(id)+","+str(someval)+")")

但我收到一个关于需要 multi=True 的错误,但将它放在 execute() 函数中似乎不像某些网站建议的那样工作,我不知道还有哪里把它放在 Django 中。

所以...我错过了什么想法?如何让存储过程工作?

【问题讨论】:

    标签: mysql django stored-procedures python-3.4 django-orm


    【解决方案1】:

    这些是我采取的以下步骤:

    1. 使我的存储过程将结果转储到临时表中,以便将结果集展平为单个结果集。这消除了对multi=True 的需要
    2. 此外,我确保使用我的 IP 地址的用户有权调用数据库本身中的存储过程。
    3. 最后,我继续研究callproc函数。最终,另一个站点上的某人建议了以下代码,该代码有效:

      cur = connections["SomeDB"].cursor()
      cur.callproc("spGetLocationPath", [id, someval])
      res = next(cur.stored_results()).fetchall()
      cur.close()
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多