matzano
matzano

Reputation: 33

How do I issue a SQL query using pyodbc that involves python variables as the parameters?

I am writing a program that searches a database and inputs the data into a excel file based on user selection from two calendars (on the GUI). I have a start and end date, I am passing those variables as parameters into a function for my SQL query.

How do I format the SQL query to select the values from the given dates?

Here is my code so far,

def load_database(startDate, endDate):

    conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
    'Server=DESKTOP-KVR7GNJ\SQLBULKROLL;' 
    'Database=db_MasterRoll;'
    'UID=sa;'
    'PWD=Z28@6420d')

    wb = Workbook()
    ws = wb.active
    ws.title = "Star Ledger"
    cursor = conn.cursor()
    cursor.execute('SELECT ID, BarCode, DateTm, EntryDoor FROM dbo.tab_Rolls WHERE (DateTm >= @startDate) AND (DateTm <= @endDate)')

a button invokes this code by running the function "call_db_code()":

def call_db_code():
    firstDate = start_dateCalendar.selection_get()
    print(firstDate)

    finalDate = end_dateCalendar.selection_get()
    print(finalDate)
    load_database(firstDate, finalDate)

Upvotes: 0

Views: 2161

Answers (1)

Barmar
Barmar

Reputation: 780798

Use ? as placeholders in the query, and provide a tuple of values to substitute for them.

cursor.execute('SELECT ID, BarCode, DateTm, EntryDoor FROM dbo.tab_Rolls WHERE (DateTm >= ?) AND (DateTm <= ?)', (startDate, endDate))

See the examples in the cursor.execute() documentation.

Upvotes: 1

Related Questions