我正在运行本地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