如何将日期变量传递给 Python 中的 SQL 查询

How to pass a date variable to an SQL query in Python

Python3.5 Sql 服务器 2012 标准版

包是 pypyodbc

此代码有效

myConnection = pypyodbc.connect('Driver={SQL Server};'
                                'Server=myserver;'
                                'Database=mydatabase;'
                                'TrustedConnection=yes')
myCursor = myConnection.cursor()
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= '7/21/2016'")
myCursor.execute(sqlstr)
results = myCursor.fetchall()

但是Date必须是用户传入的变量。我对 sqlstr 做了几个修改,但在 myCursor.execute 上继续出错:"TypeError: bytes or integer address expected instead of tuple instance"

sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= %s", '7/21/2016')

错误

sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= '%s'", '7/21/2016')

错误

sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= ?", "'7/21/2016'")

错误

var1 = "'7/21/2016'"
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= %s", var1)

还有更多。但是,我确信有一种正确的方法...

感谢您的帮助!

I am sure there is one correct way

是的,这是一个参数化查询:

date_var = datetime(2016, 7, 21)
sql = """\
SELECT [ID], [LastName], [DOB] FROM [Clients] WHERE [DOB]<?
"""
params = [date_var]  # list of parameter values
crsr.execute(sql, params)
for row in crsr.fetchall():
    print(row)