Search code examples
sql-server-2012pydevpython-3.5pypyodbc

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


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!


Solution

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