简体   繁体   中英

python database (sqlite3) and the treeview

hi everyone i have a problem in my code i try to display my tables from the data base on the treeview but i can't i see this error "TypeError: 'sqlite3.Cursor' object is not subscriptable" might be because i have three table on my data base these is a part of my code :

tv=ttk.Treeview(root)
tv.place(x=24,y=335)
style = ttk.Style(root)
style.configure('Treeview', rowheight=30)
tv.heading('#0',text="ID")
tv.column("#0",width=99)
tv.configure(column=('#Type','#Code','#Designation','#Prix achat'))
tv.heading('#Type',text="Type")
tv.heading('#Code',text="Code")
tv.heading('#Designation',text="Designation")
tv.heading('#Prix achat',text="Prix achat (DZA)")

cur=issam.tree_select()
for i in cur:
    tv.insert('','end','#{}'.format(i['ID']),text=i['ID'])
    tv.set('#{}'.format(i['ID']),'#Type',i['type'])
    tv.set('#{}'.format(i['ID']),'#Code',i['Code'])
    tv.set('#{}'.format(i['ID']),'#Designation',i['Designation'])
    tv.set('#{}'.format(i['ID']),'#Prix achat',i['pa'])

and these is the function in database file (in a class):

def tree_select(self):
    cursor=self.db.execute('SELECT * FROM poisson ')
    cur2=self.db.execute('SELECT * FROM plant')
    cur3=self.db.execute('SELECT * FROM materiel')
    return (cursor,cur2,cur3) #the problem is here 

TypeError: 'sqlite3.Cursor' object is not subscriptable

You are trying to get item from cursor, that's why.

Function tree_select returns tuple of cursors:

tree_select() -> (<sqlite3.Cursor>, <sqlite3.Cursor>, <sqlite3.Cursor>)

After it you iterate over these cursors:

cur=issam.tree_select()
for i in cur:
    ...

After it you try to extract value by key from cursor(in each iteration step):

 tv.set('#{}'.format(i['ID']),'#Type',i['type'])    # i - is sqlite3.Cursor object

where i is a sqlite3.Cursor and fails with error: 'sqlite3.Cursor' object is not subscriptable

Here is a small example, how to extract values as from dictionary:

import sqlite3

def row2dict(cursor, row):
    result = dict()
    for idx, col in enumerate(cursor.description):
        result[col[0]] = row[idx]
    return result

db = sqlite3.connect(":memory:")
db.row_factory = row2dict
cursor = db.cursor()

cursor.execute("select 1 as ID, 'john' as name")
row = cursor.fetchone()
print row['ID'], row['name']

cursor.close()
db.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM