PyQt アプリケーションを開発するために、ローカルの MySQL サーバーを実行しています。サーバーがダウンしている場合に QMessageBox を表示できれば、アプリケーションが起動しない理由をエンドユーザーが理解できるようになると便利です。
サーバーをシャットダウンして端末からプログラムを実行すると、通常の応答が返されます。
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...
「MySQL サーバーがダウンしています!」という QMessageBox を実際に表示する方法はありますか? または似たようなものですか?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.