Hello!
I have been playing around with python and mysql, and I have started thinking about creating a database to record my bird sights. For connection purposes, I have programmed this class
class LoginDlg(wx.Dialog):
def __init__(self):
wx.Dialog.__init__(self, None, -1, 'Login to Ornithobase 1.0b', size=(250,150))
def comboLogin():
import MySQLdb
db= MySQLdb.connect(host='localhost', user='root' , passwd='acrsci00', db='Ornithobase')
cursor = db.cursor()
sql = '''select Username from Users'''
cursor.execute(sql)
result = cursor.fetchall()
result2 = []
x = 0
for record in result:
for field in record:
users = str(field)
result2.append(users)
x += 1
return result2
users = comboLogin()
# widgets
userLbl = wx.StaticText(self, -1, 'Username:', size=(75, -1))
self.userTxt = wx.ComboBox(self, -1, '', size=(200, -1), choices = users)
passwordLbl = wx.StaticText(self, -1, 'Password:', size=(75, -1))
self.passwordTxt = wx.TextCtrl(self, -1, '',style=wx.TE_PROCESS_ENTER|wx.TE_PASSWORD, size=(200, -1))
loginBtn = wx.Button(self, -1, 'Login')
clearBtn = wx.Button(self, wx.ID_CLEAR, 'Clear')
self.Bind(wx.EVT_BUTTON, self.OnLogin,loginBtn)
self.Bind(wx.EVT_BUTTON, self.OnClear, clearBtn)
# sizer / layout
userSizer = wx.BoxSizer(wx.HORIZONTAL)
passwordSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
mainSizer = wx.BoxSizer(wx.VERTICAL)
userSizer.Add(userLbl, 0, wx.ALL, 5)
userSizer.Add(self.userTxt, 0, wx.ALL, 5)
passwordSizer.Add(passwordLbl, 0, wx.LEFT|wx.RIGHT, 5)
passwordSizer.Add(self.passwordTxt, 0, wx.LEFT, 5)
btnSizer.Add(loginBtn, 0, wx.ALL, 5)
btnSizer.Add(clearBtn, 0, wx.ALL, 5)
mainSizer.Add(userSizer, 0, wx.ALL, 0)
mainSizer.Add(passwordSizer, 0, wx.ALL, 0)
mainSizer.Add(btnSizer, 0, wx.ALL, 5)
# Logged in variable
self.loggedIn = False
self.SetSizer(mainSizer)
self.Fit()
self.Layout()
def OnLogin(self, event):
Username = self.userTxt.GetValue()
pwd = self.passwordTxt.GetValue()
try:
db= MySQLdb.connect(host='localhost', user=Username , passwd=pwd, db='Ornithobase')
cursor = db.cursor()
print 'Connected'
dlg = wx.MessageDialog(None, 'You are logged in', 'Info', wx.OK)
dlg.ShowModal()
self.Destroy()
except:
self.userTxt.Clear()
self.passwordTxt.Clear()
Errordlg = wx.MessageDialog(None, 'Connection failed', 'Error', wx.OK | wx.ICON_ERROR)
print 'Connection failed'
Errordlg.ShowModal()
def OnClear(self, event):
self.userTxt.Clear()
self.passwordTxt.Clear()
My immediate question is: is this database connection permanent? I mean, there will be many functionalities in the db, such as user management, data entry or queries on the entered data. Is there a way to make the login connection to last until the app is closed or should I connect every time I design a class (for example, a dialog that retrieves the logged in user's data to edit it. I hope I've explained myself well enough ...
Ciao!
Dani