python - 使用 pyodbc 将日期时间插入到 MS SQL 表中

标签 python sql-server pyodbc mssql-jdbc

我正在尝试使用 pyodbc 将日期时间值插入到 MS SQL Server 表中。 如果我手动执行,则类似:

cursor.execute("""insert into currentvalue(value1,currentdatetime)
                                    values(55,'2014-06-27 16:42:48.533')""")

我完全没有问题,但是当我尝试这样做时:

currenttime = str(datetime.datetime.now())
cursor.execute("""insert into currentvalue(value1,currentdatetime) 
                                    values(55,"""+ currenttime+")")

我遇到了这个错误:

SQL server Incorrect syntax near '07' which i think is the number after the date and starting the time.

我也试过这个:

currenttime = "'"+str(datetime.datetime.now())+"'"

现在出现这个错误:

Conversion failed when converting date and/or time from character string.

最佳答案

删除日期时间到字符串的转换并改为使用参数:

....
cursor.execute("insert into currentvalue (value1,currentdatetime) values(?,?)",
               (value1, datetime.datetime.now()))
....

关于python - 使用 pyodbc 将日期时间插入到 MS SQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458124/

相关文章:

python - 如何从pyodbc中的用户获取表名,同时避免SQL注入(inject)?

python - pyODBC:在 Windows 中指定驱动程序的位置

python - 如何使用 subprocess.call 让计算机进入休眠状态?

sql-server - 在附加数据库中创建成员表、SPROC、 View

python - 覆盖 Qt MouseEvent 但仅当类变量为 True 时

c# - 使用 async-await 进行数据库查询——这如何节省线程?

c# - 如何用SqlCommandBuilder给DataTable中的指定列加值

mysql - SQLServer pyodbc 的 Python 驱动程序比 psycopg2 和带有插入的 mysql.connector 慢得多

python - Heroku 使用 postgres 连接和 python 安排任务

python - 在 python 中,如何让我自己的异常类在 shell 中漂亮地打印出来?