mysql8使用mysqlclient報錯解決
在公司的時候搭建的專案正常執行,但回家後clone程式碼後安裝依賴包後總報錯:
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
what? 然後我解除安裝安裝了兩遍還是不行,安裝也沒有報錯。公司跟家裡的系統都是macOS10.14.3,python包也都是通過pipenv安裝的版本都是一樣的,唯一不同的是mysq版本,家裡的是8.0.12而公司是5.7。
那麼只可能是mysql版本導致的,於是上網查詢原因,首先找到一個是因為mysql8的使用者認證加密方式不同導致連不上資料庫,這應該跟我的情況不同,因為看報錯明顯是因為找不到mysqlclinet
包,
但還是得試一試,而且既然有這原因,肯定後面也會遇到。
-- 由caching_sha2_password加密方式改為mysql_native_password ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword'; FLUSH PRIVILEGES;
果然還是不好使,後來找到mysqlclient的github頁面
按照其為macOS安裝了mysql-connector-c
也不好使,並且查看了mysql_congfig
也沒有其提到的問題。
後來只好自己查看了報錯位置的程式碼:
try: import MySQLdb as Database except ImportError as err: raise ImproperlyConfigured( 'Error loading MySQLdb module.\n' 'Did you install mysqlclient?' ) from err
我自己debug了這段程式碼發現在匯入的時候報缺少了某個.so
,正好我又查到了一條相關問題。連結地址如下
不是那條改用pymysql
的回覆,不過改用pymsql
應該也好使,我也記錄一下:
# 安裝pymysql,在setting.py同級目錄的__init__.py里加入以下兩行程式碼 import pymysql pymysql.install_as_MySQLdb()
對我有用的是這條回覆:
I had this issue just recently even with using the python 3 compatible mysqlclient library and managed to solve my issue albeit in a bit of an unorthodox manner. If you are using MySQL 8, give this a try and see if it helps! :) I simply made a copy of the libmysqlclient.21.dylib file located in my up-to-date installation of MySQL 8.0.13 which is was in /usr/local/mysql/lib and moved that copy under the same name to /usr/lib. You will need to temporarily disable security integrity protection on your mac however to do this since you won’t have or be able to change permissions to anything in /usr/lib without disabling it. You can do this by booting up into the recovery system, click Utilities on the menu at the top, and open up the terminal and enter csrutil disable into the terminal. Just remember to turn security integrity protection back on when you’re done doing this! The only difference from the above process will be that you run csrutil enable instead. You can find out more about how to disable and enable macOS’s security integrity protection here.
回覆中說啟用mac的csrutil,然後把/usr/local/mysql/lib中的libmysqlclient.21.dylib拷貝到/usr/lib中。其實不用這麼幹,直接軟連過去就可以
sudo ln -s /usr/local/mysql/lib/libmysqlclient.21.dylib /usr/lib/libmysqlclient.21.dylib
再執行django就沒有報錯了