I am trying to run a SQL statement with a user input in where clause

If the following code it runs great. However, I want to be able to have the user be able to enter the DeptName in the where clause. I have tried several ways using v1 = input(“Enter DeptName:”) but nothing works, in the ways that I am trying.

Any ideas would be appreciated.
Thanks

import pyodbc
#v1 = input("Enter DeptName: ")
conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=DESKTOP-MCd2;"
                      "Database=North2;"
                      "Trusted_Connection=yes;")

cursor = conn.cursor()

cursor. Execute("SELECT * FROM EmpDetails where DeptName = 'CCC'")

print('EmpId ' + 'DeptId ' + 'DeptName')
for row in cursor:
    print('%r' % (row,))

Try something like this (untested):

deptname = input("Enter department name: ")

cursor.execute("select * from EmpDetails where DeptName = ?",
               (deptname,))
...

Notes:

  • Never manually construct a full SQL statement using raw user input! The form I used above relies on the database adaptor to escape the user input.
  • I don’t use pyodbc. I don’t know what its argument placeholder is. I guessed “?”. Check the value of pyodbc.paramstyle to see what it is.

More details about Python’s database API can be found in PEP 249.

Hi,
Thanks for your reply and help I will try this.
Thanks