[Python] ModuleNotFoundError: No module named ‘mysql’

在測試 mysql 8.0 官方給的範例小程式:
https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

範例:

import mysql.connector
cnx = mysql.connector.connect(user='max', password='password',
                               host='127.0.0.1',
                               database='employees', auth_plugin='mysql_native_password')
cnx.close()

顯示錯誤訊息:

ModuleNotFoundError: No module named 'mysql'

這個問題在 macOS 會遇到,升級python 3.7 到 python 3.8 也會遇到。

在 macOS / ubuntu 裡服用下列的指令,安裝完 connector 後就可以直接執行無誤:

for python 2:

python -m pip install mysql-connector-python

for python 3:

python3 -m pip install mysql-connector-python

解法:

在 mysql 官網站下載 connector 並「關閉」terminal 後重新開啟 terminal 重新執行你的 python script 即可正常執行:
https://dev.mysql.com/downloads/connector/python/


如果在Ubuntu 遇到,請服用下面的指令:

The solution is to install corresponding Python 3 module:

sudo apt-get install python3-mysql.connector

It fixes import mysql.connector error:

$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>> 

And similar for Python 2:

sudo apt-get install python-mysql.connector

$ python2
Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>> 

相關文章:

Python 連 mysql
https://stackoverflow.max-everyday.com/2017/09/python-mysql/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *