pythonmysqlubuntu-16.04mysql-python

AttributeError: module 'mysql' has no attribute 'connector'


I'm running Ubuntu 16.04, trying to connect to mysql in python:

    import mysql
    username = 'root'

    cnx = mysql.connector.connect(user=username, database='db')
    cnx.close()

But I get an error:

    File "pysql1.py", line 4, in <module>
      cnx = mysql.connector.connect(user=username, database='db')
    AttributeError: module 'mysql' has no attribute 'connector'

I installed the mysql python module by downloading the package here. I tried sudo apt-get install python-mysql.connector to no avail. Any pointers?

EDIT: after adding import mysql.connector I got an unrelated permissions error which I've now resolved, so that's what I needed ty lots!!!


Solution

  • The solution is to execute :

    import mysql.connector # or from mysql import connector
    

    Because the module connector is only available when you import it explicitly :

    import mysql
    
    print(dir(mysql))
    >>> ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', 
    '__package__', '__path__', '__spec__']
    
    import mysql.connector
    
    print(dir(mysql))
    >>> ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', 
    '__package__', '__path__', '__spec__', 'connector']
    

    The __init__ file in the module mysql doesn't import the module connector.

    mysql
    |_______ __init__.py # no import at this level
    |_______ connector
             |________ __init__.py
    

    This could work implicitly if connector was imported inside __init__ with : from . import connector.