简体   繁体   中英

Execute a SQL Stored Procedure within a Python Script

I'm trying to execute a SQL stored proc within a Python script and having issues with the syntax. I have tried a combination of various examples I have found but none seem to work. Here's what I have tried:

county = 100200
confirmed = 123456
death = 12
labTestCount = 0    
#Example1
conn.execute('{CALL [spInsertCOVIDData](@County,@Confirmed,@Death,@LabTestCount)}', ('county', 'confirmed', 'death', 'labTestCount'))

#Example2
query = "EXEC [spInsertCOVIDData] (@County,@Confirmed,@Death,@LabTestCount)", (county, confirmed, death, labTestCount)
conn.execute(query)

#Example3
query = "EXEC [spInsertCOVIDData] @County=?, @Confirmed=?, @Death=?, @LabTestCount=?",(county, confirmed, death, labTestCount)
conn.execute(query)

#Example4
query = "EXEC [spInsertCOVIDData] @County='county', @Confirmed='confirmed', @Death='death', @LabTestCount='labTestCount'"
conn.execute(query)

I get a mixture of various error from:

('The SQL contains 0 parameter markers, but 4 parameters were supplied', 'HY000')

or

The first argument to execute must be a string or unicode query.

You may try to use parameters in your statement using ? as a placeholder and pass the actual values of each parameter:

county = 100200
confirmed = 123456
death = 12
labTestCount = 0

query = "EXEC [spInsertCOVIDData] @County=?, @Confirmed=?, @Death=?, @LabTestCount=?"
conn.execute(query, (county, confirmed, death, labTestCount))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM