Hướng dẫn python execute stored procedure with output parameter - python thực thi thủ tục lưu trữ với tham số đầu ra

Tôi sử dụng pyodbc và sau đó chuyển đổi đối tượng hàng pyodbc thành một danh sách. Hầu hết các câu trả lời cho thấy một truy vấn khai báo các biến là một phần của truy vấn. Nhưng tôi sẽ nghĩ rằng bạn tuyên bố các biến của bạn là một phần của SP, do đó loại bỏ một bước không cần thiết trong Python. Sau đó, trong Python, tất cả những gì bạn phải làm là truyền các tham số để điền vào các biến đó.

Dưới đây là chức năng tôi sử dụng để chuyển đổi đối tượng ROWS PYODBC thành danh sách có thể sử dụng [danh sách] [lưu ý rằng tôi đã nhận thấy PyoDBC đôi khi thêm các không gian theo dõi, vì vậy tôi giải thích cho tôi hoạt động tốt cho tôi]:

def convert_pyodbc[pyodbc_lst]:
'''Converts pyodbc rows into usable list of lists [each sql row is a list],
   then examines each list for list elements that are strings,
   removes trailing spaces, and returns a usable list.'''
usable_lst = []
for row in pyodbc_lst:
    e = [elem for elem in row]
    usable_lst.append[e]
for i in range[0,len[usable_lst[0]]]:
    for lst_elem in usable_lst:
        if isinstance[lst_elem[i],str]:
            lst_elem[i] = lst_elem[i].rstrip[]
return usable_lst

Bây giờ nếu tôi cần chạy một quy trình được lưu trữ từ Python trả về một bộ kết quả, tôi chỉ cần sử dụng:

strtdate = '2022-02-21'
stpdate = '2022-02-22'

conn = mssql_conn['MYDB']
cursor = conn.cursor[]

qry = cursor.execute[f"EXEC mystoredprocedure_using_dates 
'{strtdate}','{stpdate}' "]
results = convert_pyodbc[qry.fetchall[]]

cursor.close[]
conn.close[]

Và kết quả mẫu mà sau đó tôi lấy và ghi vào bảng tính hoặc w/e:

[[datetime.date[2022, 2, 21], '723521', 'A Team Line 1', 40, 9], 
[datetime.date[2022, 2, 21], '723522', 'A Team Line 2', 15, 10], 
[datetime.date[2022, 2, 21], '723523', 'A Team Line 3', 1, 5], 
[datetime.date[2022, 2, 21], '723686', 'B Team Line 1', 39, 27], 
[datetime.date[2022, 2, 21], '723687', 'B Team Line 2', 12, 14]]

#**********************************************************************
# FILENAME :    CallSPWithInOutParam.c
#
# DESCRIPTION :
#               This example shows how, using SELECT at the end of a stored
#               procedure, the generation of basic return values and output
#               variables, can be implemented in pyodbc.
#
#               Here we want to call a stored procedure that returns a status
#               value, takes one input parameter and returns an output
#               parameter, in the form:
#
#               {? = CALL InOutRet_Params [?, ?]}
#
#               In pyodbc the only option available for returning values is
#               via data generated by a SELECT, which can then be picked up
#               by fetchone[] or fetchall[]. This example shows how to use
#               this method and returning values other than record sets.
#
# ODBC USAGE :
#

#
#               Connects to Data Source using Data Source Name
#               Creates cursor on the connection
#               Drops and recreates a procedure 'pyFind_Record'
#	        Loops asking user to input a PersonID [until zero or
#               invalid number entered].
#                   Executes the procedure using cursor.execute[]
#                   Calls cursor.fetchall[] to retrieve any row found
#                   For each row, displays column values
#   	            Returns number of matching records in table
#                   Returns error status
#               Closes and deletes cursor and closed connection
#
#
import pyodbc

# If OUTPUT and RETURN values were properly supported in python, the call
# to the procedure could be {?=CALL pyInOutRecs[?,?]} where parameter 1 is
# a return value, parameter 2 could be input and paramater 3 could be output.
# To do this we have to have the call as {CALL pyInOutRecs[?]} with just
# the input parameter. The RETURN value and the OUTPUT parameters are
# returned in a rowset generated by additional SELECT statements. See below.
# These can then be retrieved using cursor.nextset[] follows by
# cursor.fetchone[] or cursor.fetchall[] for each.
sqlCreateSP="CREATE PROCEDURE pyInOutRet_Params [\
             @pPersonID int] AS \
             DECLARE @MatchingRecs int; \
             DECLARE @RetCode int; \
             SELECT PersonID, FirstName, LastName, Address, City \
             FROM TestTBL1 WHERE PersonID=@pPersonID; \
             SELECT @MatchingRecs=count[*] FROM TestTBL1 WHERE \
             PersonID=@pPersonID; \
             SELECT @MatchingRecs;\
             SET @RetCode=@@ERROR; \
             SELECT @RetCode;"

# Drop Stored Procedure Statement
sqlDropSP="IF EXISTS [SELECT * FROM sys.objects \
           WHERE type='P' AND name='pyInOutRet_Params'] \
           DROP PROCEDURE pyInOutRet_Params"

# Call Stored Procedure Statement
sqlExecSP="{call pyInOutRet_Params [?]}"

# Connect to data source
conn=pyodbc.connect['DSN=DATASOURCE', autocommit=True]

# Create cursor associated with connection
cursor=conn.cursor[]

print "\nStored Procedure is : pyInOutRet_Params"

# Drop SP if exists
cursor.execute[sqlDropSP]

# Create SP using Create statement
cursor.execute[sqlCreateSP]

# Loop - prompt for record details, insert and get results returned
while 1:

    # Get PersonId to look up
    userInput=raw_input["\nPerson ID : "]

    # Check positive integer entered, quit if
    # negative or not a number
    try:
        id=int[userInput]
    except ValueError:
        id=0
        if userInput != "":
            print "\nSorry, NAN"

    if id

Bài Viết Liên Quan

Chủ Đề