Skip to content
Advertisement

How to use variables in SQL query when using Python and pyodbc

I am using Python to extract data from SQL by using ODBC to linking Python to SQL database. when I do the query, I need to use variables in the query to make my query result changeable. For example, my code is:

You can see that I retrieve data from SQL database and save it into a list (Result), then I convert this list to a data frame (d).

But, my problems are:

  1. I need to specify a start date and an end data in myCursor.execute part, something like "CALDAY" BETWEEN Start AND End
  2. Let’s say I have 100 offices in my data. Now I just need 3 of them (myOffice). So, I need to put a condition in myCursor.execute part, like myOffice in (1,2,3)

In R, I know how to deal with these two problems. the code is like:

But I do not know how to do this in Python. How can I do this?

Advertisement

Answer

You can use string formatting operations for this.

First define

Now you can use

and

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement