Need Help Optomizing Code

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew

    Need Help Optomizing Code

    Hi I am fairly new to python

    and was wondering if anyone out there could help me optomize this code.

    It is a simple Tkinter program that connects to a database and deletes
    records

    Some of this code was borrowed from a book learning python

    Anyhelp would be cool thank you in advance

    Andrew

    """""Below is the code"""""

    import MySQLdb
    from Tkinter import *

    class FormEditor:

    def __init__(self):


    self.row = 0
    self.current = None

    self.root = root = Tk()
    root.minsize(30 0, 200)


    root.rowconfigu re(0, weight=1)
    root.columnconf igure(0, weight=1)
    root.columnconf igure(1, weight=2)


    Label(root, text='Form Editor App', font='bold').gr id(columnspan=2 )
    self.row = self.row + 1
    self.listbox = Listbox(root, selectmode=SING LE)
    self.listbox.gr id(columnspan=2 , sticky=E+W+N+S)
    self.listbox.bi nd('<ButtonRele ase>')
    self.row = self.row + 1

    self.add_button (self.root, self.row, 0, 'Delete Entry',
    self.delentry)
    self.add_button (self.root, self.row, 1, 'Reload', self.load_data)

    self.load_data( )


    def add_button(self , root, row, column, text, command):
    button = Button(root, text=text, command=command )
    button.grid(row =row, column=column, sticky=E+W, padx=5, pady=5)

    def load_data(self) :
    self.db = MySQLdb.connect ("localhost" , "", "", "guestbook" )
    self.c = self.db.cursor( )
    self.c.execute( "select * from guests;")
    self.results = self.c.fetchall ()
    self.listbox.de lete(0, END)
    for item in self.results:
    self.listbox.in sert(END, item)

    def delentry(self):
    self.db = MySQLdb.connect ("localhost" , "", "", "guestbook" )
    self.c = self.db.cursor( )
    self.c.execute( "DELETE FROM guests WHERE id LIMIT 1;")
    self.results = self.c.fetchall ()
    print "Please press reload to see your results"


    app = FormEditor()
    app.mainloop()


  • Rene Pijlman

    #2
    Re: Need Help Optomizing Code

    Andrew:[color=blue]
    >and was wondering if anyone out there could help me optomize this code.[/color]
    [...][color=blue]
    > self.db = MySQLdb.connect ("localhost" , "", "", "guestbook" )
    > self.c = self.db.cursor( )
    > self.c.execute( "DELETE FROM guests WHERE id LIMIT 1;")[/color]
    ^^^^^^^^^^^^^^^ ^
    What does that mean?
    [color=blue]
    > self.results = self.c.fetchall ()[/color]

    In general, it's unwise to reconnect to a database server for every single
    data manipulation. Keep the connection open, and perhaps even the cursor.
    But I'm not sure if and how this works precisely with MySQL, I prefer
    PostgreSQL myself.

    Also, you seem to be forgetting the commit and disconnect.

    --
    René Pijlman

    Comment

    Working...