Bug #118826 msql.connector.connect does not exist using mysql.connector.python
Submitted: 13 Aug 16:39 Modified: 19 Aug 10:07
Reporter: Keith Wetzel Email Updates:
Status: Not a Bug Impact on me:
None 
Category:MySQL Server Severity:S3 (Non-critical)
Version:9.4 OS:Windows (11)
Assigned to: CPU Architecture:x86

[13 Aug 16:39] Keith Wetzel
Description:
I've installed MySQL Server 9.4, Python 3.13.5, mysql-connector-python-9.4.0.  I've copied both "connect" code examples from Chapter 5.1 of the MySQL Connector/Python Developer Guide.  Below are the results on my Windows 11 laptop.

import mysql.connector
cnx = mysql.connector.connect(user='keith',
                              password='*',
                              host='localhost')
cnx.close()

Traceback (most recent call last):
  File "c:\mysql\doc_connector_ex.py", line 3, in <module>
    cnx = mysql.connector.connect(user='keith',
          ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'mysql.connector' has no attribute 'connect'

from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='keith',
                                 password='*',
                                 host='localhost')
cnx.close()

Traceback (most recent call last):
  File "c:\mysql\doc_connector_ex2.py", line 1, in <module>
    from mysql.connector import (connection)
ImportError: cannot import name 'connection' from 'mysql.connector' (unknown location). Did you mean: 'connector'?

This happens when running in VSCode or the Bash CLI.

Is the doco obsolete?  Please advise.

How to repeat:
See description
[19 Aug 10:07] MySQL Verification Team
This is not a bug.

Are you sure you properly installed everything. Here is the simple example that works just tested on win11, MySQL 9.5, python 13.5.7

pip install -r .\requirements.txt
...
Successfully installed mysql-connector-python-9.4.0 protobuf-4.21.12 python-dotenv-1.0.0

cat requirements.txt
mysql-connector-python==9.4.0
python-dotenv==1.0.0

cat test.py
#!/usr/bin/env python3
"""
Simple Python app to connect to MySQL and fetch data from mysql.users table
"""

import os
import sys
import mysql.connector
from mysql.connector import Error
from dotenv import load_dotenv

def load_config():
    """Load configuration from environment variables or config file"""
    # Try to load from .env file first
    if os.path.exists('.env'):
        load_dotenv('.env')
    elif os.path.exists('config.env'):
        load_dotenv('config.env')
    
    # Get configuration from environment variables
    config = {
        'host': os.getenv('DB_HOST', 'localhost'),
        'port': int(os.getenv('DB_PORT', 3306)),
        'user': os.getenv('DB_USER'),
        'password': os.getenv('DB_PASSWORD'),
        'database': os.getenv('DB_NAME', 'mysql')
    }
    
    # Check if required credentials are provided
    if not config['user'] or not config['password']:
        print("Error: Database username and password are required.")
        print("Please set DB_USER and DB_PASSWORD environment variables or create a .env file.")
        print("You can copy config.env.example to .env and fill in your credentials.")
        return None
    
    return config

def connect_to_mysql(config):
    """Establish connection to MySQL database"""
    try:
        connection = mysql.connector.connect(
            host=config['host'],
            port=config['port'],
            user=config['user'],
            password=config['password'],
            database=config['database']
        )
        
        if connection.is_connected():
            print(f"Successfully connected to MySQL database '{config['database']}' on {config['host']}:{config['port']}")
            return connection
        else:
            print("Failed to connect to MySQL database")
            return None
            
    except Error as e:
        print(f"Error connecting to MySQL: {e}")
        return None

def fetch_users(connection):
    """Fetch all records from mysql.users table"""
    try:
        cursor = connection.cursor()
        
        # Execute the query
        query = "SELECT * FROM mysql.users;"
        print(f"Executing query: {query}")
        
        cursor.execute(query)
        
        # Fetch all results
        results = cursor.fetchall()
        
        # Get column names
        column_names = [desc[0] for desc in cursor.description]
        
        print(f"\nFound {len(results)} records in mysql.users table:")
        print("-" * 80)
        
        # Print column headers
        print(" | ".join(column_names))
        print("-" * 80)
        
        # Print each row
        for row in results:
            print(" | ".join(str(value) if value is not None else "NULL" for value in row))
        
        print("-" * 80)
        
        cursor.close()
        return results
        
    except Error as e:
        print(f"Error executing query: {e}")
        return None

def main():
    """Main function"""
    print("MySQL Users Table Fetcher")
    print("=" * 40)
    
    # Load configuration
    config = load_config()
    if not config:
        sys.exit(1)
    
    # Connect to MySQL
    connection = connect_to_mysql(config)
    if not connection:
        sys.exit(1)
    
    try:
        # Fetch and display users
        fetch_users(connection)
        
    except KeyboardInterrupt:
        print("\nOperation cancelled by user")
    except Exception as e:
        print(f"Unexpected error: {e}")
    finally:
        # Close connection
        if connection and connection.is_connected():
            connection.close()
            print("\nMySQL connection closed")

if __name__ == "__main__":
    main()