PyODBC, cursor.execute() won't insert parameters into SQL String

时光毁灭记忆、已成空白 提交于 2019-12-02 10:04:30

Use datetime.strptime() to convert the attack_datetime value to a datetime object before passing the value to SQL Server.

For example, passing a datetime formatted string fails with the same error message you receive

...
# assumes connection and cursor objects initialized
create_date_str = "2016-06-16T01:23:45.67890"
sql = "select name, create_date from sys.databases where create_date = ?"
rows = cursor.execute(sql, create_date_str).fetchall()

Raises

Traceback (most recent call last): File "", line 1, in pyodbc.DataError: ('22007', '[22007] [Microsoft][SQL Server Native Client 11.0][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)')

While converting the datetime string to a datetime object succeeds

...
# convert datetime string to object, specifying input format
create_date = datetime.datetime.strptime(create_date_str, '%Y-%m-%dT%H:%M:%S.%f')
rows = cursor.execute(sql, create_date).fetchall()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!