问题
I try to write function for my project, which allows user partial search and highlights rows/records according to column "name" with sqlite3 statements. But I dont know how to wrie the function that it works with SQLite3 statement and matches rows/records in treeview.
def saerch_medicine():
#query with sqlite3
conn = sqlite3.connect("pharmacy.db")
cur = conn.cursor()
conn.commit()
cur.execute("SELECT name FROM medicine WHERE name LIKE '%"name_column"%'")
selections=[]
for i in cur:
tree. selections[0]
conn.close()
bt6 = Button(root,text="Serach according column name",width=10,command=saerch)
bt6.grid(row=11,column=1,pady=10,padx=20)
e6 = Entry(root,width=20)
e6.grid(row=11,column=3,pady=10,padx=20)
回答1:
Assume the first column in the tree
is the name
column, then modify saerch_medicine()
(should saerch
be search
instead?) as below:
def saerch_medicine():
srch_name = e6.get().strip()
if srch_name:
conn = sqlite3.connect("pharmacy.db")
cur = conn.cursor()
cur.execute('SELECT name FROM medicine WHERE name LIKE "%{}%"'.format(srch_name))
matched = [rec[0] for rec in cur]
conn.close()
items = [row for row in tree.get_children() if tree.item(row, 'values')[0] in matched]
tree.selection_set(items)
However if all the records have been inserted into tree
, I think you can search the tree
directly:
def saerch_medicine():
srch_name = e6.get().strip()
if srch_name:
rows = [row for row in tree.get_children() if srch_name in tree.item(row, 'values')[0]]
tree.selection_set(rows)
来源:https://stackoverflow.com/questions/63061035/quering-in-database-sqlite3