0

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)
Charlie Clark
19.7k4 gold badges56 silver badges64 bronze badges
asked Jun 19, 2020 at 21:08

1 Answer 1

1

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.

answered Jun 19, 2020 at 21:17
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.