ModuleNotFoundError: No module named ‘mysql.connector’; ‘mysql’ is not a package

resotto
2 min readAug 24, 2019

When I tried to connect to MySQL via Python3 program, I encountered problem above.

At first, I had surely installed mysql-connector-python before running the program.

pip3 install mysql-connector-python(For readability, added line feed to each row)Requirement already satisfied: mysql-connector-python in /opt/pypy3.6-v7.1.1-osx64/site-packages (8.0.17)Requirement already satisfied: protobuf>=3.0.0 in /opt/pypy3.6-v7.1.1-osx64/site-packages (from mysql-connector-python) (3.9.1)Requirement already satisfied: six>=1.9 in /opt/pypy3.6-v7.1.1-osx64/site-packages (from protobuf>=3.0.0->mysql-connector-python) (1.12.0)Requirement already satisfied: setuptools in /opt/pypy3.6-v7.1.1-osx64/site-packages/setuptools-40.8.0-py3.6.egg (from protobuf>=3.0.0->mysql-connector-python) (40.8.0)

The program mysql.py was:

import mysql.connectorif __name__ == '__main__':
con = mysql.connector.connect(
user='remote',
password='password',
host='0.0.0.0',
database='mydb'
)
cur = con.cursor()
cur.execute('select * from stock;')
for row in cur.fetchall():
print(row[0], row[1])
cur.close()
con.close()

And then, I ran the program via pypy3 .

pypy3 mysql.pyTraceback (most recent call last):
File "mysql.py", line 1, in <module>
import mysql.connector
File "/Users/resotto/develop/sandbox/mysql/mysql.py", line 1, in <module>
import mysql.connector
ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package

The cause of this problem was the name of the python3 program, mysql.py .

In order to solve this problem, I needed to understand following two things:

  • When import statement is used, Python searches specified package/module from current directory.
  • .py file means it is a python module.

connector module was in mysql package, and also I named my own python3 program as mysql.py .

In short, I imported not mysql-connector-python module, but my own mysql module.

That’s why the above error said:

‘mysql’ is not a package

Actually, ‘mysql’ was module of my own.

So, I changed the program name to mysql_temp.py , and it worked well.

pypy3 mysql_temp.py1 eraser
2 banana
3 apple
4 orange
5 ballpoint-pen

That’s it! Thanks.

--

--