[Python] My PyQt6 interface freezes when connecting to MySQL

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    This is my code to connect to MySQl

    class MySQLWorker(QObject): finished = pyqtSignal(bool, str)
    def run(self):
    try:
    db = mysql.connector.connect(
    host="127.0.0.1",
    user="root",
    password="",
    database="quanlyvanphongpham"
    )
    if db.is_connected():
    self.finished.emit(True, "✅ Successfully connected to MySQL!")
    except mysql.connector.Error as e:
    self.finished.emit(False, f"❌ MySQL connection error: {e}")

    class StationaryStoreApp(QMainWindow):
    def __init__(self):
    super().__init__()
    self.initUI()
    self.start_mysql_connection() # Run MySQL connection on a separate thread

    def start_mysql_connection(self):
    self.thread = QThread() # Create a separate thread
    self.worker = MySQLWorker()
    self.worker.moveToThread(self.thread) # Move worker to the thread

    # Connect signals
    self.thread.started.connect(self.worker.run)
    self.worker.finished.connect(self.handle_mysql_result)
    self.worker.finished.connect(self.thread.quit) # Exit thread when done
    self.worker.finished.connect(self.worker.deleteLater)
    self.thread.finished.connect(self.thread.deleteLater)

    self.thread.start() # Start the thread

    def handle_mysql_result(self, success, message):
    print(message)


    I tried running on a separate thread but it still resulted in a frozen interface and MySql always reported: Aborted connection 177 to db: 'unconnected' user: 'unauthenticated' host: 'localhost' (Got an error reading communication packets)

    Continue reading...

Compartilhe esta Página