Loading text boxes with DB values from Combobox Selection

Question:

I’m trying to populate values in text boxes from existing db based on selection made by user in GUI via combobox.

def lookupClassification(event):
    # clear the text boxes
    rate.delete(0, END)
    burden_factor.delete(0, END)
    total_cost.delete(0, END)

    # Create a database or connect to one
    conn = sqlite3.connect('labor_rates.db')
    # Create a cursor
    c = conn.cursor()

    classification_selected = classification.get()
    #query the database
    c.execute('SELECT * FROM laborrates WHERE classification = ?', [classification_selected])
    records = c.fetchall()
    #loop through results
    for record in records:
        rate.insert(0, record[1])
        burden_factor.insert(0, record[2])
        total_cost.insert(0, record[3])
        
#combobox options
def class_combo():
    conn = sqlite3.connect('labor_rates.db')
    c = conn.execute('SELECT classification FROM laborrates')
    result = []
    for row in c.fetchall():
        result.append(row[0])
    return result

# create text boxes
classification = ttk.Combobox(lr_editor, width = 30, values = class_combo())
classification.grid(row=1, column=1, padx=20, pady=(10,0))
classification.bind('<<ComboboxSelected>>', lookupClassification)

Once the selection is made no values are populated within the respected text boxes. I’ve tried all I can think of and would appreciate any insite.

Asked By: Worm

||

Answers:

If column classification is a string and for example classification_selected = "Foreman", then the final SQL of

'SELECT * FROM laborrates WHERE classification = ' + classification_selected

will be

SELECT * FROM laborrates WHERE classification = Foreman

It will cause the exception mentioned in the comment.

It is better to use placeholder in the SQL in order to avoid SQL injection:

c.execute('SELECT * FROM laborrates WHERE classification = ?', [classification_selected])
Answered By: acw1668
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.