AminTN
AminTN

Reputation: 110

MySQL causing the PyQT5 to quit suddenly

I started coding a data repository in Python. I have to use MySQL connector. There is an issue that's causing me headaches and I have to get the project read. I have coded the user interface in PyQT5 and whenever I try to use my data repository the application closes suddenly. The repository works on its own without issues but inside PyQT5 app it doesn't

Here's the code for the repo db.py


import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode

class Database:
    def __init__(self):
        self.dbc = ("localhost","db", "user", "pass")

    def __enter__(self):
        try:
            self._conn = mysql.connector.connect(host = self.dbc[0], database = self.dbc[1], user = self.dbc[2] , password = self.dbc[3])
            self._cursor = self._conn.cursor(dictionary=True)
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                    print("Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                    print("Database does not exist")
            else:
                    print(err)
            raise
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
           self._cursor.close()
           self._conn.close()
        except AttributeError: # isn't closable
            print('Not closable.')
            return True # exception handled successfully

    def commit(self):
        self._conn.commit()

    def close(self, commit=True):
        if commit:
            self.commit()
        self._conn.close()

    def ping_connection(self):
        if not self._conn.is_connected():
            self._conn.reconnect()

    def fetch_all(self, query: str, params: tuple = None) :
        self.ping_connection()
        self._cursor.execute(query, params or ())
        result = self._cursor.fetchall() 
        return result  
        
    def get_list(self) :
            sql = """SELECT * from Users;"""
            return self.fetch_all(sql)
    
if __name__ == "__main__":
    with Database() as db:
            print(db.get_list())

the error I get is

Exception ignored on threading shutdown:
Traceback (most recent call last):
  File "C:\Users\amuser\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 1524, in _shutdown
    if _main_thread._handle.is_done() and _is_main_interpreter():
SystemError: <method 'is_done' of '_thread._ThreadHandle' objects> returned a result with an exception set

a simple QT gui like this would cause the app to quit suddenly

from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QMessageBox
import sys
from db import Database

class TestDialog(QDialog):
    def __init__(self):
        super(TestDialog, self).__init__()
        self.setWindowTitle("Test Dialog")

        # Create a button and set its position and size
        self.test_button = QPushButton("Click Me", self)
        self.test_button.setGeometry(50, 50, 100, 30)
        
        # Connect the button click event to the `on_button_click` method
        self.test_button.clicked.connect(self.on_button_click)

    def on_button_click(self):
        # Show a message box when the button is clicked
        with Database() as db:
            result = db.get_list()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dialog = TestDialog()
    dialog.show()
    sys.exit(app.exec_())

those are the installed packages

Package                Version
---------------------- ---------
certifi                2024.8.30
charset-normalizer     3.4.0
guidata                3.1.0
guiqwt                 4.4.4
h5py                   3.12.1
idna                   3.10
mysql-connector-python 9.1.0
numpy                  2.1.3
packaging              24.2
pillow                 11.0.0
pip                    24.3.1
pyqt-tools             1.0.0
PyQt5                  5.15.11
PyQt5-Qt5              5.15.2
PyQt5_sip              12.15.0
PythonQwt              0.14.1
QtPy                   2.4.2
requests               2.32.3
scipy                  1.14.1
tomli                  2.1.0
urllib3                2.2.3

What could be issue?

Thank you

Upvotes: 1

Views: 43

Answers (0)

Related Questions