I am trying to do something like this in Python,
SQLCommand = ("Delete From %s where [Date] >= %s and [Date] <= %s", (calendar_table_name, required_starting_date, required_ending_date))
cursor.execute(SQLCommand)
calendar_table_name is a string variable
required_starting_date is a datetime variable
required_ending_date is a datetime variable
Trying this gives me an error:
The first argument to execute must be a string or unicode query.
Tried this and it gives me the same error:
SQLCommand = ("Delete From " + calendar_table_name + " where [Date] >= %s and [Date] <= %s", ( required_starting_date, required_ending_date))
cursor.execute(SQLCommand)
Edit:
type(required_ending_date)
Out[103]: pandas._libs.tslibs.timestamps.Timestamp
type(required_starting_date)
Out[103]: pandas._libs.tslibs.timestamps.Timestamp
This works in SSMS for me,
delete from [table_test] where [Date] >= '2007-01-01' and [Date] <= '2021-01-01';
Update :- This is the code, that I am trying with
Delete_SQLCommand = f"Delete FROM [{calendar_table_name}] WHERE [Date]>=? And [Date]<=?"
params = (required_starting_date, required_ending_date)
required_starting_date & required_ending_date are of "TimeStamp" formats
calendar_tbl_connection = pyodbc.connect(driver=driver, server=required_server, database=database_name,
trusted_connection='yes')
calendar_tbl_cursor = calendar_tbl_connection.cursor()
calendar_tbl_cursor.execute(Delete_SQLCommand,params)
calendar_tbl_connection.commit
calendar_tbl_connection.close()
From %s whereis not valid in this case. You need to use string formatting to make dynamic table names, then pass the parameters for the rest of the queryexecute().datetimeobject and not a string, and either the column is configured to take TEXT values (or similar) or your connection library won't do the conversion to ISO formatSQLCommandbe just the string portion, i.e.SQLCommand = "Delete From ...". Then call execute with the arguments:cursor.execute(SQLCommand, (arg1, arg2))