1

Python3.5 Sql Server 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)

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

谢谢你的帮助!

4

1 回答 1

2

我确信有一种正确的方法

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

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)
于 2016-07-26T13:08:21.117 回答