Django:在OS X環境下鏈接MySQL數據庫

安裝庫

正常的安裝只須要執行如下2條命令:php

$ brew install mysql-connector-c
$ pip3 install mysqlclient

但在執行 pip3 install mysqlclient時,出現報錯:python

which ()
{
  IFS="${IFS=   }"; save_ifs="$IFS"; IFS=':'
  for file
  do
:112
      File "<string>", line 1, in <module>
      File "/private/var/folders/k9/q3cgwmcx4l51554_97h5rx4h0000gn/T/pip-install-n_ai97oc/mysqlclient/setup.py", line 16, in <module>
        metadata, options = get_config()
      File "/private/var/folders/k9/q3cgwmcx4l51554_97h5rx4h0000gn/T/pip-install-n_ai97oc/mysqlclient/setup_posix.py", line 63, in get_config
        libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')]
      File "/private/var/folders/k9/q3cgwmcx4l51554_97h5rx4h0000gn/T/pip-install-n_ai97oc/mysqlclient/setup_posix.py", line 63, in <listcomp>
        libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')]
      File "/private/var/folders/k9/q3cgwmcx4l51554_97h5rx4h0000gn/T/pip-install-n_ai97oc/mysqlclient/setup_posix.py", line 12, in dequote
        raise Exception("Wrong MySQL configuration: maybe https://bugs.mysql.com/bug.php?id=86971 ?")
    Exception: Wrong MySQL configuration: maybe https://bugs.mysql.com/bug.php?id=86971 ?
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/k9/q3cgwmcx4l51554_97h5rx4h0000gn/T/pip-install-n_ai97oc/mysqlclient/

緣由是,MySQL Connector/C使用了錯誤的默認配置,致使在Mac OS X下編譯出錯。mysql

所以,解決方法就是修改該默認配置。sql

執行命令 which mysql_config 以查看配置文件(mysql_config)的具體路徑.數據庫

$ which mysql_config
/usr/local/bin/mysql_config   # 輸出了配置文件的真實路徑

用你熟悉的編輯器打開該文件, 定位到112行。django

#原配置是:
# Create options
libs="-L$pkglibdir"
libs="$libs -l "

#修改爲如下:
# Create options
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

最後再執行前面的 $ pip3 install mysqlclient, 已經能夠正常安裝了。編輯器

Django配置

打開settings.py文件,修改 「DATABASES」設置code

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  #驅動名【保持默認】
        'NAME': 'housework',                                     #要鏈接的數據庫名【改爲你的數據庫名】
        'HOST': '127.0.0.1',                                     #數據庫地址【本地數據庫保持默認就行】
        'POST': 3306,                                                    #數據庫端口【默認】
        'USER': 'root',                                              #你的數據庫登陸名
        'PASSWORD': 'admin12345',                            #你的數據庫登陸密碼
    }
}

到目前爲止,Django就和數據庫創建鏈接了。ip

附上官方文檔: https://pypi.org/project/mysqlclient/ssl

相關文章
相關標籤/搜索