Worm
Worm

Reputation: 19

Loading text boxes with DB values from Combobox Selection

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.

Upvotes: 0

Views: 82

Answers (1)

acw1668
acw1668

Reputation: 47163

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])

Upvotes: 1

Related Questions