Home > Back-end >  Check if the contents of a combobox are present in the database
Check if the contents of a combobox are present in the database

Time:10-12

If in the combobox I select the element Drake, I would like to check if this element is present in the database (SQLite) in the name field. What am I doing wrong?

I do not receive errors, but I print "ok" for each selection of the combobox. For example "Tom" is not present in the database, but I still print "ok": it is not correct

from tkinter import ttk
import tkinter as tk
from tkinter import *
import sqlite3

root = tk.Tk()
root.geometry("350x200")

con = sqlite3.connect('/home/fred/Desktop/test2.db')
cursor = con.cursor()

combo1=ttk.Combobox(root, width = 22)
combo1['value'] =["Drake", "Richard"] #and other 17 name
combo1.place(x=10, y=10)
combo1.set("Select")

def my_function():
    if  cursor.execute("SELECT 1 FROM Table1 WHERE name = ?", (combo1.get(),)):
        print("ok")

btn = Button(root, text="Click", command = my_function)
btn.place(x=10, y=50)

CodePudding user response:

Your assumption about cursor.execute seems to be wrong. It doesn't return a result you can evaluate with if. After cursor execution you need to call cursor.fetchall() docs and check its returned list. In case of "Tom" that list should be empty:

def my_function():
    cursor.execute("SELECT 1 FROM Table1 WHERE name = ?", (combo1.get(),))
    if cursor.fetchall():
        print("ok")
  • Related