我似乎无法使用Python将DateTime插入SQL Server。
这是我的代码:
def execute_query_commit(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed and committed")
except pyodbc.Error as e:
print(f"The error '{e}' occurred")
email = input("Email: ")
credcard = int(input("Enter number:"))
now = datetime.now()
query = f'''
insert into testing1 (email, credcard, transactiondetails)
values ({email},{credcard},{now})'''
conn = create_connection()
execute_query_commit(conn,query)
SQL Server 中transactiondetails
列的数据类型是日期时间。
如果我对值进行硬编码:'2020-06-03 18:09:23'
- 它有效。
但是,如果我使用{now}
,错误发生在18
The error '('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '18'. (102) (SQLExecDirectW)")' occurred
有没有人知道如何解决这个问题?
如果你要传入python datetime.now((,那么你需要格式化字符串
f = '%Y-%m-%d %H:%M:%S'
now.strftime(f)
但是我建议参数化SQL