syyed syyed - 5 months ago 32
Python Question

SQL Server Error converting data type nvarchar to date python

I am getting an error while calling Sql store procedure in python.

SQL Server Error converting data type nvarchar to date.

My code is as below.

from datetime import datetime

OnlyDate=datetime.now().date()

# I got date in OnlyDate in this formate :-2016-06-30

self.con.execute("exec dbo.ScrapeStatistics_SP @Op='6',@EndTime=now,@Site='testing',@ScrapeType='Category',@Date=OnlyDate")
self.con.commit()

Answer

@Date=OnlyDate

You are trying to insert the string OnlyDate into the Date column, therefore ending up with an error that nvarchar ("OnlyDate") can't be converted to date.

You should use a parameterized query:

query = "exec dbo.ScrapeStatistics_SP @Op='6',@EndTime=now,@Site='testing',
           @ScrapeType='Category',@Date=?"

self.con.execute(query , (OnlyDate,))  # note the comma! this needs to be a tuple
Comments