使用pymssql将datetime对象插入SQL

2024-10-06 13:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用pymssql插入datatime对象?我知道SQL Server表需要一个datetime对象,比如说在位置3。我试过这三种方法:

cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', datetime.datetime.now())")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', 20130410)")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', '20130410')")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', GETDATE())")

每次我都会得到同样的错误:

OperationalError: (241, 'Conversion failed when converting date and/or time from character string.DB-Lib error message 241, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')

我搜遍了那里的小文件,反复搜遍了。


Tags: 对象fromexecutesqldatetimeservermytableerror
3条回答

您试图插入一个未格式化为日期的字符串(datetime.datetime.now(),20130410,'20130410',GETDATE()),因此sql server无法从中分析日期。。。

所以试试这个。。。

cursor.execute("
    INSERT INTO MyTable
    VALUES(
        1,
        'Having Trouble',
        '" + str(datetime.datetime.now()) + "'
    )
")

您可以使用以下代码:

# a tuple with the data to be stored in db
data = (1, 'Having Trouble', datetime.datetime.now())
# perform the query 
cursor.execute("INSERT INTO MyTable VALUES(%s, %s, %s)" % data)

试试这个:

timeStamp = str(datetime.datetime.now())[0:-3]

此时间戳格式可由MS SQL SERVER转换,并可在PymSQL中用于插入datetime类型的对象

相关问题 更多 >