0

I am trying to insert the current datetime into a datetime2 type column of a SQL Server table:

creationdatetime = datetime.datetime.now() # 2021-11-20 21:35:40.851495

sql = ("INSERT INTO [SCHEMA].[TABLE] (\n"
        "[CreationDateTime]) \n"
        f"VALUES ('{creationdatetime}')")

cursor.execute(sql)
cursor.commit() 

I keep on getting this error:

[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '2021'. (102) (SQLExecDirectW)

Already spent like 3 hours to fix this issue....

Any help is really appreciated

Thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Anouar
  • 85
  • 5
  • 5
    If you parametrise, rather than inject, this issue disappears. Plus your code then doesn't have a huge security vulnerability. Learn from the mistakes of others from the last decades: Parametrise. – Thom A Nov 20 '21 at 20:58
  • After parametrisation it worked fine, Thank you – Anouar Nov 20 '21 at 21:36
  • 2
    You could add the updated, parametrized code as an answer and as an example for others who might be facing the same issue – marc_s Nov 20 '21 at 21:48

0 Answers0