am have created a table using treeview and i would like to insert in data fetched from mysql table.if any one can help me because i have tried all my level best but still in vain.with this statement tree.insert("", 1, text=2, values=("name", "5", "5")) can insert well data but not from the database, but i would like to fetch from the database and display it.
here is the code i have tried but it has failed.please help.
`
from Tkinter import *
import ttk
import MySQLdb
root = Tk()
root.geometry("320x240")
tree = ttk.Treeview(root)
conn = MySQLdb.connect("localhost", "root", "drake", "OSCAR")
cursor = conn.cursor()
tree["columns"] = ("one", "two", "three")
tree.column("one", width=100)
tree.column("two", width=100)
tree.column("three", width=100)
tree.heading("#0", text='ID', anchor='w')
tree.column("#0", anchor="w")
tree.heading("one", text="NAME")
tree.heading("two", text="VOTES")
tree.heading("three", text="PERSENTAGE")
for i in range(1, 6):
cursor.execute("""select name from president where ID =%s""", (i,))
nm = cursor.fetchone()[0]
cursor.execute("""select votes from president where ID =%s""", (i,))
vot = cursor.fetchone()[0]
cursor.execute("""select percentage from president where ID =%s""",(i,))
percent = cursor.fetchone()[0]
tree.insert("", i, text=i, values=(nm, vot, percent)),
tree.pack()
root.mainloop()
`
解决方案
To resolve your problem, first you will need to read all the rows of the database using this query:
SELECT * FROM president
which you need to execute:
cursor.execute("""SELECT * FROM president""")
Now, simply loop over the rows and insert them one by one in tree:
UPDATE:
I suppose your table structure is like this:
ID | name | votes | percentage
So you could run this:
cpt = 0 # Counter representing the ID of your code.
for row in cursor:
# I suppose the first column of your table is ID
tree.insert('', 'end', text=str(cpt), values=(row[1], row[2], row[3]))
cpt += 1 # increment the ID