无法将 DateTime 从 Python 插入 SQL 服务器

Can't insert DateTime into SQL Server from Python

我似乎无法使用 Python

将 DateTime 插入 SQL 服务器

这是我的代码:

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 服务器中 transactiondetails 列的数据类型是 DateTime。

如果我对值进行硬编码:'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