'I can't recover Sql data from combobox. Error: 'NoneType' object is not subscriptable
By selecting an item in the combobox, I would like to retrieve the database row that has the same name selected by the combobox in one of the fields.
For example, if in the combobox there is Tokyo, Madrid, London, Paris (obtained from the "example" column of the database) and I select Tokyo, I would like the row that has the text "Tokyo" in the "example" column to be searched in the database table. Then print the row separately.
I get the error when I try and retrieve and print the data:
TypeError: 'NoneType' object is not subscriptable
While tweaking the code a bit and trying to fix it, I no longer get the error, but the variables are printed as None, None, None, None.
I don't need the function ad i don't need a button. I would simply like that by selecting the combobox, the variables are printed.
Can anyone help me? Thank you
import sqlite3
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
root.geometry('400x400')
root.config(bg="gray")
root.state("normal")
conn = sqlite3.connect('....')
cursor = conn.cursor()
def view_combobox():
cursor.execute('SELECT example FROM material LIMIT 2 OFFSET 2')
values = [row[0] for row in cursor]
return values
example=ttk.Combobox(root, width = 21)
example.place(x=10, y=10)
example.set("Select")
example['value'] = view_combobox()
select_example__button3 = example.get()
#################################################
#PROBLEM IS HERE
if select_example__button3:
cursor.execute('SELECT a, b, c, d FROM material WHERE example=?', (select_example__button3,))
value = cursor.fetchone()
print(value[0], value[1], value[2], value[3], value[4])
Database
CREATE TABLE "material" (
"id" INTEGER,
"a" INTEGER,
"b" INTEGER,
"c" INTEGER,
"d" INTEGER,
"example" TEXT,
PRIMARY KEY("id")
NOTE: I have tested that if I insert the condition inside a function and then call the function with a button, I no longer receive the error and the variables are printed correctly. But it was just a test, I DON'T NEED THE FUNCTION, AND I DON'T NEED A BUTTON. I would simply like that by selecting the combobox, the variables are printed
Solution 1:[1]
Have you checked the value return from cursor.fetchone(). If due to any reason if it returns empty resultset it returns None. So check the value obtained from cursor.fetchone() if it is not None then only print the value as
cursor.execute('SELECT a, b, c, d FROM material WHERE example=?', (select_example__button3,))
value = cursor.fetchone()
if value is not None:
print(value[0], value[1], value[2], value[3], value[4])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user8193706 |
