Python Forum
Errors during run .exe file generated with Pyinstaller
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Errors during run .exe file generated with Pyinstaller
#1
Hello,

I'm just starting my adventure with Python, so please bear with me.

I wrote a script that deletes a database.

I wanted the script to be run using batch. That's why I decided to generate an .exe file using Pyinstaller.

Unfortunately, when I try to run the .exe I get errors.

My code below:

delete_orpheus_db.py

import mysql.connector
from mysql.connector import Error
from config import get_config

def delete_orpheus_database():
    try:
        connection = mysql.connector.connect(
            host= get_config()['host'],
            user= get_config()['user'], 
            password= get_config()['password']
        )

        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("DROP DATABASE orpheus")
            print("Database 'orpheus' successfully deleted.")

    except Error as e:
        print(f"Test connection failed. Error: {e}")
        
    finally:
        if connection.is_connected():
            cursor.close() 
            connection.close()
            print("Database connection closed.")
config.py

import json

def get_config():
    with open('C:/Repositories/ORPHEUS/DB/CONFIG/config.json',"r") as config_file:
        config  = json.load(config_file)

    return config
config.json

{
    "host":"localhost",
    "user":"root", 
    "password":"11111111", 
    "database": "orpheus"
}
I call this line in CMD in folder with my delete_orpheus_db.py

pyinstaller --onefile delete_orpheus_db.py
And here is error which I got after run .exe file

C:\Users\mnawr>delete_orpheus_db.bat
Traceback (most recent call last):
  File "delete_orpheus_db.py", line 9, in delete_orpheus_database
  File "mysql\connector\pooling.py", line 322, in connect
  File "mysql\connector\connection_cext.py", line 153, in __init__
  File "mysql\connector\abstracts.py", line 1529, in connect
  File "mysql\connector\connection_cext.py", line 365, in _open_connection
RuntimeError: Failed raising error.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "delete_orpheus_db.py", line 29, in <module>
  File "delete_orpheus_db.py", line 24, in delete_orpheus_database
UnboundLocalError: cannot access local variable 'connection' where it is not associated with a value
[PYI-27856:ERROR] Failed to execute script 'delete_orpheus_db' due to unhandled exception!
I think that I forgot about something but I have no idea what it is.
Thanks a lot for any help!
Have a good day
Reply
#2
Initialize connection outside the try block.
In the finally block, check if connection is not None before attempting to access its methods.
import mysql.connector
from mysql.connector import Error
from config import get_config

def delete_orpheus_database():
    connection = None  # Initialize connection
    try:
        connection = mysql.connector.connect(
            host=get_config()['host'],
            user=get_config()['user'], 
            password=get_config()['password']
        )

        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("DROP DATABASE orpheus")
            print("Database 'orpheus' successfully deleted.")
    except Error as e:
        print(f"Test connection failed. Error: {e}")
    finally:
        if connection is not None and connection.is_connected():
            cursor.close()
            connection.close()
            print("Database connection closed.")

if __name__ == "__main__":
    delete_orpheus_database()
You most bundled config.json with the executable.
pyinstaller --onefile --add-data "C:/Repositories/ORPHEUS/DB/CONFIG/config.json;." delete_orpheus_db.py
BushyAxis793 likes this post
Reply
#3
(Mar-23-2025, 12:13 PM)snippsat Wrote: Initialize connection outside the try block.
In the finally block, check if connection is not None before attempting to access its methods.
import mysql.connector
from mysql.connector import Error
from config import get_config

def delete_orpheus_database():
    connection = None  # Initialize connection
    try:
        connection = mysql.connector.connect(
            host=get_config()['host'],
            user=get_config()['user'], 
            password=get_config()['password']
        )

        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("DROP DATABASE orpheus")
            print("Database 'orpheus' successfully deleted.")
    except Error as e:
        print(f"Test connection failed. Error: {e}")
    finally:
        if connection is not None and connection.is_connected():
            cursor.close()
            connection.close()
            print("Database connection closed.")

if __name__ == "__main__":
    delete_orpheus_database()
You most bundled config.json with the executable.
pyinstaller --onefile --add-data "C:/Repositories/ORPHEUS/DB/CONFIG/config.json;." delete_orpheus_db.py

Thank you very much for reply! I added validation to my code and now my code is:

import mysql.connector
from mysql.connector import Error
from config import get_config

def delete_orpheus_database():
    connection = None
    try:
        connection = mysql.connector.connect(
            host= get_config()['host'],
            user= get_config()['user'], 
            password= get_config()['password']
        )

        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("DROP DATABASE orpheus")
            print("Database 'orpheus' successfully deleted.")

    except Error as e:
        print(f"Test connection failed. Error: {e}")
        
    finally:
        if connection is not None and connection.is_connected():
            cursor.close() 
            connection.close()
            print("Database connection closed.")
But I still get the error

Traceback (most recent call last):
  File "delete_orpheus_db.py", line 28, in <module>
  File "delete_orpheus_db.py", line 8, in delete_orpheus_database
  File "mysql\connector\pooling.py", line 322, in connect
  File "mysql\connector\connection_cext.py", line 153, in __init__
  File "mysql\connector\abstracts.py", line 1529, in connect
  File "mysql\connector\connection_cext.py", line 365, in _open_connection
RuntimeError: Failed raising error.
[PYI-5084:ERROR] Failed to execute script 'delete_orpheus_db' due to unhandled exception!
Reply
#4
The error can comes from MySQL Connector’s C extension,C extension often isn’t bundled correctly leading to the “Failed raising error”.
One workaround is to force MySQL Connector to use its pure-Python implementation rather than the C extension.
import mysql.connector
from mysql.connector import Error
from config import get_config

def delete_orpheus_database():
    connection = None
    try:
        config = get_config()
        connection = mysql.connector.connect(
            host=config['host'],
            user=config['user'], 
            password=config['password'],
            use_pure=True   # Force pure Python implementation
        )

        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("DROP DATABASE orpheus")
            print("Database 'orpheus' successfully deleted.")
    except Error as e:
        print(f"Test connection failed. Error: {e}")
    finally:
        if connection is not None and connection.is_connected():
            cursor.close() 
            connection.close()
            print("Database connection closed.")

if __name__ == "__main__":
    delete_orpheus_database()
BushyAxis793 likes this post
Reply
#5
(Mar-23-2025, 05:37 PM)snippsat Wrote: The error can comes from MySQL Connector’s C extension,C extension often isn’t bundled correctly leading to the “Failed raising error”.
One workaround is to force MySQL Connector to use its pure-Python implementation rather than the C extension.
import mysql.connector
from mysql.connector import Error
from config import get_config

def delete_orpheus_database():
    connection = None
    try:
        config = get_config()
        connection = mysql.connector.connect(
            host=config['host'],
            user=config['user'], 
            password=config['password'],
            use_pure=True   # Force pure Python implementation
        )

        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute("DROP DATABASE orpheus")
            print("Database 'orpheus' successfully deleted.")
    except Error as e:
        print(f"Test connection failed. Error: {e}")
    finally:
        if connection is not None and connection.is_connected():
            cursor.close() 
            connection.close()
            print("Database connection closed.")

if __name__ == "__main__":
    delete_orpheus_database()

Thanks for reply! I found one more error:

C:\Users\mnawr>delete_orpheus_db.bat Requested Module was not found: No module named 'mysql.connector.plugins.mysql_native_password' Traceback (most recent call last): 
File "delete_orpheus_db.py", line 29, in <module> 
File "delete_orpheus_db.py", line 8, in delete_orpheus_database 
File "mysql\connector\pooling.py", line 323, in connect 
File "mysql\connector\connection.py", line 187, in init 
File "mysql\connector\connection.py", line 459, in close 
File "mysql\connector\connection.py", line 1060, in cmd_quit 
File "mysql\connector\network.py", line 651, in send 
File "mysql\connector\network.py", line 224, in send 
File "mysql\connector\network.py", line 170, in send_pkt 
File "mysql\connector\errors.py", line 60, in init 
File "mysql\connector\locales_init.py", line 62, in get_client_error ImportError: No localization support for language 'eng' [PYI-17668:ERROR] Failed to execute script 'delete_orpheus_db' due to unhandled exception!
And I found a solution:

pyinstaller --onefile --hidden-import=mysql.connector.plugins.mysql_native_password delete_orpheus_db.py
It seems to be working fine! Thank you very much for your help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Executable file compiled by PyInstaller does not work on Windows 7 amusaber 1 1,844 Jul-11-2024, 02:59 PM
Last Post: DeaD_EyE
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 7,991 Jun-27-2023, 01:17 PM
Last Post: diver999
  HOW TO USE C# GENERATED DLL davide_vergnani 2 3,294 Jun-12-2023, 03:35 PM
Last Post: davide_vergnani
  Trying to access excel file on our sharepoint server but getting errors cubangt 0 1,497 Feb-16-2023, 08:11 PM
Last Post: cubangt
  Formating generated .data file to XML malcoverc 3 2,113 Apr-14-2022, 09:41 PM
Last Post: malcoverc
  Pyinstaller distribution file seems too large hammer 4 4,958 Mar-31-2022, 02:33 PM
Last Post: snippsat
  How to add product details in exe generated by pyinstaller arex786 1 12,003 Oct-10-2021, 11:00 AM
Last Post: Sran012
  problem with pyinstaller to create an executable file atlass218 0 3,258 May-15-2021, 11:01 AM
Last Post: atlass218
  Pyinstaller create this error :“File ”multiprocessing\connection.py“, line 691 Formationgrowthhacking 2 4,722 Apr-30-2020, 10:26 AM
Last Post: buran
  the exe file by generated by pyinstaller ,can't get the PYTHONPATH roger2020 11 9,810 Jan-14-2020, 11:07 AM
Last Post: roger2020

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020