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.

Answer

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))

Leave a Reply

Your email address will not be published. Required fields are marked *