Python3.5 Sql Server 2012 Standard
包是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做了几个mod但在myCursor.execute上继续出错:&#34; TypeError:期望的字节或整数地址而不是tuple实例&#34;
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)
还有几个。但是,我确信有一种正确的方法......
感谢您的帮助!
答案 0 :(得分:1)
我确信有一种正确的方法
是的,它是参数化查询:
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)