0

I have two tables, department and job and I want to connect them in an employee form. I have a QCombobox that displays department names taken directly from SQL Server and I want to add another combobox that displays values based on the department combobox.

The tables are:

dept_id dept
1 dept 1
2 dept 2
3 dept 3
job_id job dept_id
1 job 1 2
2 job 2 1
3 job 3 1

So far I've written:

    def jobcombobox(self):
    conn = pyodbc.connect(connection)
    cursor = conn.cursor()

    dept_index = self.department.currentIndex()
    cursor.execute("SELECT job, job_id FROM jobs WHERE dept_id =" %dept_index)
    rows = cursor.fetchall()

    for row in rows:
        self.job.addItem(str(row[0]), row[1])
        print(row)

I've changed dept_idex to

cursor.execute("SELECT job, job_id FROM jobs WHERE dept_id ={dept_index}")

but no luck. What am I doing wrong?

  • Both syntaxes are wrong: the `%` one is missing the % placeholder in the string (https://docs.python.org/3/library/stdtypes.html#old-string-formatting), the `{}` is missing the `f` prefix (https://docs.python.org/3/reference/lexical_analysis.html#f-strings). Read those links carefully and do research on their usage. Also you should *never* create queries formatting strings, as they don't support escaping and are a serious security risk. Use parameters as arguments of `execute()`. See https://stackoverflow.com/a/902417 – musicamante Feb 23 '22 at 16:08

0 Answers0