我正在運行本地MySQL服務器來開發我的PyQt應用程序。如果服務器關閉時可以顯示QMessageBox會很好,所以最終用戶會有一些想法,爲什麼應用程序不能啓動。在QMessageBox中顯示MySQL錯誤
如果我關閉服務器和終端運行我的程序,我得到的通常的反應:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (2)")
我的代碼很簡單
import pymysql as lite
con = lite.connect(host='127.0.0.1',unix_socket='/run/mysqld/mysqld.sock', user='ivica',passwd='pass',db='baza',charset='utf8')
#define one class that inherits QMainWindow and so on...
有沒有辦法對我來說,實際上顯示一個QMessageBox,聲明「MySQL服務器已關閉!」或類似的東西?如果MySQL服務器沒有運行,我的應用程序窗口甚至不會顯示,只是終端錯誤。
:編輯:
修改建議後,我的代碼看起來是這樣的:
con = None #this is how I make it global, eg. not in any method or class (?)
def dbconnect():
global con
#con = None
try:
if os.name == 'nt':
con = lite.connect(host='127.0.0.1', user='ivica',passwd='pass',db='baza',charset='utf8')
else:
con = lite.connect(host='127.0.0.1',unix_socket='/run/mysqld/mysqld.sock', user='ivica',passwd='pass',db='baza',charset='utf8')
except lite.err.OperationalError as err:
msgBox = QtGui.QMessageBox()
msgBox.setText(str(err))
msgBox.show()
return con
class Logon(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.ui=Ui_dlgLogovanje()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.dugmeUloguj, QtCore.SIGNAL("clicked()"), self.doLogin)
def doLogin(self):
with dbconnect():
cur = dbconnect().cursor()
和錯誤我得到的是:
Traceback (most recent call last):
File "main.py", line 59, in doLogin
with dbconnect():
AttributeError: __exit__
:編輯2:
後unutbu的回答,以及我的一些代碼的擺弄,這是我正在尋找的解決方案:
con = None
def dbconnect():
global con
try:
if os.name == 'nt':
con = lite.connect(host='127.0.0.1', user='ivica',passwd='pass',db='baza',charset='utf8')
else:
con = lite.connect(host='127.0.0.1',unix_socket='/run/mysqld/mysqld.sock', user='ivica',passwd='pass',db='baza',charset='utf8')
except lite.err.OperationalError as err:
msgBox = QtGui.QMessageBox()
msgBox.setText(str(err))
msgBox.show()
return con
class Logon(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.ui=Ui_dlgLogovanje()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.dugmeUloguj, QtCore.SIGNAL("clicked()"), self.doLogin)
def doLogin(self):
if con == None:
reply = QtGui.QMessageBox.warning(self, 'Greška',
"Can't establish connection to database!", QtGui.QMessageBox.Ok)
if reply == QtGui.QMessageBox.Ok:
self.close() #and when user clicks OK program closes
else:
with dbconnect():
cur = dbconnect().cursor()
#do other database stuff, check credentials etc.
只有當'lite.connect'失敗時纔得到這個'AttributeError',或者即使建立了成功的連接,你也能得到它嗎? – unutbu
如果沒有運行MySQL服務器,那是我得到的錯誤。如果服務器運行一切都很好,沒有錯誤。 – ivica
連接失敗時,'con'等於'None',它沒有'__exit__'方法。這就是爲什麼'with dbconnect()'失敗。如果連接失敗,您希望發生什麼? – unutbu