Django Call Stored Procedure on Second Database

2019-05-22 23:01发布

I'm trying to call a stored procedure on a multi-db Django installation, but am not having any luck getting results. The stored procedure (which is on the secondary database) always returns an empty array in Django, but the expected result does appear when executed in a mysql client.

My view.py file from SomeDBModel import models from django.db import connection

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

I have also tried:

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

Each time I print out the results, I get:

[]

Example of data that should be retrieved:

{
    Path: '/some/path/', 
    LocalPath: 'S:\Some\local\Path', 
    Folder: 'SomeFolderName', 
    Code: 'SomeCode'
}

One thing I also tried was to print the result of cursor.callproc. I get:

(id, someval)

Also, printing the result of cursor._executed gives:

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

Which seems to not have any reference to the stored procedure I want to run at all. I have even tried this as a last resort:

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

but I get an error about needing multi=True, but putting it in the execute() function doesn't seem to work like some sites have suggested, and I don't know where else to put it in Django.

So...any ideas what I missed? How can I get stored procedures to work?

1条回答
冷血范
2楼-- · 2019-05-22 23:28

These are the following steps that I took:

  1. Made my stored procedure dump results into a temporary table so as to flatten the result set to a single result set. This got rid of the need for multi=True
  2. In addition, I made sure the user at my IP address had access to call stored procedures in the database itself.
  3. Finally, I continued to research the callproc function. Eventually someone on another site suggested the following code, which worked:

    cur = connections["SomeDB"].cursor()
    cur.callproc("spGetLocationPath", [id, someval])
    res = next(cur.stored_results()).fetchall()
    cur.close()
    
查看更多
登录 后发表回答