1

Python3.5 Sql Server 2012 Standard

package is pypyodbc

This Code Works

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()

However, Date must be a variable passed in by users. I made several mods to sqlstr but continue to error on 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')

Error

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

Error

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

Error

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

and several more. However, I am sure there is one correct way...

Thanks for any help!

1 Answer 1

2

I am sure there is one correct way

Yes, it's a parameterized query:

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that did the trick. For anyone curious about multiple parameters, simply separate with comma [param1, param2, param3]. Also, I did not have to edit the entire query to be parameterized, only the variables needed to be wrapped in brackets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.