I am a real noob, so I hope someone can help me easily. I want to delete all rows with specific date (min_date) or later. Here's the code:
import pandas as pd
import pyodbc
print()
print("please wait while I import your file")
print()
data = pd.read_excel (r'C:\Users\xxx\OneDrive - xxx\Temp\2020_12_xxx.xlsx')
df = pd.DataFrame(data)
df = df.fillna(value=" ")
df['To_date']=pd.to_datetime(df['To_date'])
print(df)
min_date = df['To_date'].min()
print()
print("Data is loaded from:")
print()
print(min_date)
print()
print("data is in DataFrame, please wait")
print()
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=xxx.net;'
'Database=yyy;'
'Persist Security Info=False;'
'Authentication=ActiveDirectoryIntegrated')
cur = conn.cursor()
cur.execute('DELETE FROM FMK WHERE To_Date >= min_date')
conn.commit()
Now, when I run it I get the error message:
ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'min_date'. (207) (SQLExecDirectW)")
As you can see min_date is a variable which comes from the DF. I just would nog expect to have to put in a column name there. What am I doing wrong?
CodePudding user response:
min_date
in the query is just a plain string and as you noticed in the Error message, It's considered as a column name, So, instead of that, you need to place it in a placeholder.
cur.execute('DELETE FROM FMK WHERE To_Date >= %s', min_date)
or
cur.execute("""DELETE FROM FMK WHERE To_Date >= '{0}'""".format(min_date))