python - 在 QMessageBox 中显示 MySQL 错误

标签 python mysql error-handling pyqt qmessagebox

我正在运行本地 MySQL 服务器来开发我的 PyQt 应用程序。如果我可以在服务器关闭时显示 QMessageBox,那就太好了,这样最终用户就会知道为什么应用程序没有启动。

如果我关闭服务器并从终端运行我的程序,我会得到通常的响应:

pymysql.err.OperationalError: (2003,“无法连接到‘127.0.0.1’(2) 上的 MySQL 服务器”)

我的代码很简单

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.

最佳答案

使用 try... except block 来处理 OperationalError 异常:

import sys
from PyQt4 import QtGui
import pymysql as lite


def dbconnect():
    global con
    config = {
        'host' : '127.0.0.1',
        'user' = 'ivica',
        'passwd' = 'pass',
        'db' = 'baza',
        'charset' = 'utf8'
        }
    try:
        if os.name == 'nt':
            con = lite.connect(**config)
        else:
            con = lite.connect(unix_socket = '/run/mysqld/mysqld.sock', **config))
    except lite.err.OperationalError as err:
        msgBox = QtGui.QMessageBox()
        msgBox.setText(str(err))
        msgBox.exec_()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    con = None
    dbconnect()
    if con is not None:
        sys.exit(app.exec_())
<小时/>

看来MySQL连接是你程序的核心部分,所以你不妨一开始就建立连接,如果连接过程不成功就退出。

另外,使用

with dbconnect():
    ...

与定义全局con不兼容,因为当Python退出with block 时连接会关闭。

关于python - 在 QMessageBox 中显示 MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12429353/

相关文章:

python - Keras Sklearn RandomizedSearchCV GPU OOM 错误

python - Keras 模型通过编译但在运行时因值错误而崩溃

php - 如何将 PHP 邮件程序发送到通过 MySQL 查询收到的多个电子邮件地址

error-handling - 在web2py的数据库支持的 View 中检查有效/现有ID的标准代码是什么?

python - 从 pandas 数据框中删除已知的异常值

mysql - 连接三个表并保留空字段

mysql - sql中按日期排序

php - 捕获并调试偶发的500错误

php - fatal error : Call to a member function get_cart_contents_count() on a non-object in/functions. php 在第 413 行

python - Python 前标签之间的解析