Skip to content Skip to sidebar Skip to footer

Python: Modulenotfounderror: No Module Name 'mysql'

Trying to connect python to MySQL. Seem to be a lot on this issue but nothing seems to be working for me. If I am at the Python prompts I can enter my script line by line and hav

Solution 1:

Use pip to search the available module

$ pip search mysql-connector | grep --color mysql-connector-python
   

mysql-connector-python-rf (2.2.2)        - MySQL driver written in Python
mysql-connector-python (2.0.4)           - MySQL driver written in Python

Install the mysql-connector-python-rf

$ pip install mysql-connector-python-rf

Verify

$ python
Python 2.7.11 (default, Apr 262016, 13:18:56)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits"or"license"for more information.
>>> import mysql.connector
>>>

For python3 and later use the next command: $ pip3 install mysql-connector-python-rf

Solution 2:

You can use sys module to find out the path from where mysql is getting imported.

In the example, I can see that my OS module is getting imported from /usr/lib/python3.8/os.py

>>>import sys>>>import os>>>sys.modules['os']
<module 'os' from '/usr/lib/python3.8/os.py'>
>>>

Then add that path to your PYTHONPATH so that python can import modules from there.

See another example below:

user@user-Inspiron:~$ python3
Python 3.8.5 (default, Jul 282020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample_module
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
ModuleNotFoundError: Nomodule named 'sample_module'>>>user@user-Inspiron:~$ echo $PYTHONPATH

user@user-Inspiron:~$ export PYTHONPATH=/tmp/user@user-Inspiron:~$ echo $PYTHONPATH
/tmp/user@user-Inspiron:~$ python3
Python 3.8.5 (default, Jul 282020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample_module
>>> sample_module.does_it_work
'It Works!'>>>

Post a Comment for "Python: Modulenotfounderror: No Module Name 'mysql'"