Home > front end >  View the contents of a database column inside the combobox
View the contents of a database column inside the combobox

Time:09-17

I would like to view the contents of a database column inside the combobox. I know it's easy, yet I can't. I'm just starting out with Python. I must have made a mess and something wrong. How can I do?

Please show me the code in the answer, both because being new to Python I might not understand, and because this way I can assign the best answer. Thanks

Updated my code

import sqlite3

con = sqlite3.connect('folder db')
cursor = con.cursor()

def combo_city():
    cursor.execute('SELECT City FROM Table1')
    result=[row[0] for row in cursor]
    return result


city=ttk.Combobox(window, width = 25)
city['value'] = combo_city()
city.place(x=13, y=80)
city.set("Select")

CodePudding user response:

You first need to connect to the database then execute the required SQL statement. You should then use cursor.fetchall() or cursor.fetchone() or cursor.fetchmany(size) depending on your requirement.

Here is an example.

import sqlite3
import tkinter as tk
from tkinter import ttk
from itertools import chain


def create_db():

    with sqlite3.connect("sample.db") as conn:
        conn.cursor().executescript("""
                            CREATE TABLE IF NOT EXISTS table1(city VARCHAR(30) PRIMARY KEY);
                            INSERT OR IGNORE INTO table1 VALUES ('Tokoyo'), ('New York');
                            """)

def load_combobox():

     with sqlite3.connect("sample.db") as conn:
        cur = conn.execute("SELECT city FROM table1")
        cities = list(chain.from_iterable(cur.fetchall()))
        combo.config(values=cities)

root = tk.Tk()

combo = ttk.Combobox(root)
combo.pack()

create_db()
load_combobox()

root.mainloop()

relevant links for you to explore with statement, executescript, itertools.chain.from_iterable()

  • Related