Ошибка при установке mysqlclient python

I installed Python 2.7.15rci and Python 3.6.7 on Ubuntu. When i did ‘pip list’ on virtualenv it returns me:

Django (2.1.5)
pip (9.0.1)
pkg-resources (0.0.0)
pytz (2018.9)
setuptools (39.0.1)
wheel (0.32.3)

I’m trying to install mysqlclient (pip install mysqlclient) and returns an error.

  unable to execute 'x86_64-linux-gnu-gcc': No such file or directory
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for mysqlclient
  Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient ... error
    Complete output from command /home/david/env/project/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-pq18uxjj/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-y28h4ou0-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/david/env/project/include/site/python3.6/mysqlclient:
    /usr/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type'
      warnings.warn(msg)
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-3.6
    creating build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb
    creating build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    running build_ext
    building 'MySQLdb._mysql' extension
    creating build/temp.linux-x86_64-3.6
    creating build/temp.linux-x86_64-3.6/MySQLdb
    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,4,1,'final',0) -D__version__=1.4.1 -I/usr/include/mysql -I/home/david/env/project/include -I/usr/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o
    unable to execute 'x86_64-linux-gnu-gcc': No such file or directory
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

    ----------------------------------------
Command "/home/david/env/project/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-pq18uxjj/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-y28h4ou0-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/david/env/project/include/site/python3.6/mysqlclient" failed with error code 1 in /tmp/pip-build-pq18uxjj/mysqlclient/

So, I have tried different methods found like:

sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev

and some more… but none of them work for me and the problem persists.
Any suggestions?

Thank you!

В Django изначально реализована поддержка баз данных MySQL и MariaDB. Общение с этими базами выполняется через разные библиотеки, в том числе mysqlclient. Библиотека mysqlclient является самой быстрой и рекомендуемой при работе с Django и MySQL, но ее установка не всегда очевидна и вы можете столкнуться с рядом проблем.

Библиотеки для работы с MySQL в Python

Скорее всего их больше, какие-то библиотеки более не поддерживаются, но обычно выделяют 3 варианта для работы с базами MySQL в Python:

  • mysqclient — библиотека написанная на С, которая компилируется при установке. Является форком старого проекта MySQLdb1, который давно не поддерживается. Рекомендуется разработчиками Django и имеет самые высокие показатели производительности из остальных;
  • mysql-connector-python — это официальная библиотека от Oracle. На момент написания статьи можно встретить информацию, что разработчики переписали ее на Python 3, но это не так. Библиотека написана на Python 2.7, а поддержка этой версии закончилась в Django 2.0. В документации Django, почему-то, до сих пор можно прочитать о поддержке этого модуля. Библиотека имела самые низкие показатели скорости;
  • pymysql — сторонний проект написанные на Python 3. Django официально не поддерживает эту библиотеку. Создана теми же разработчиками, что и mysqlclient.

При установке библиотеки mysqlclient, на любой платформе (особенно на Windows), могут быть проблемы с компиляцией. Часть ошибок, которые у вас могут появиться:

  • django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
  • building ‘_mysql’ extension error: Microsoft Visual C++ 14.0 is required.
  • ModuleNotFoundError: No module named ‘MySQLdb’

Если у вас есть похожие проблемы, то я бы рекомендовал использовать mysqlclient на сервере (как самую быструю библиотеку), а pymysql использовать локально. О том как это сделать и как можно исправить ошибки написано далее.

Само собой статья исключает ситуацию, что вы можете использовать PostgreSQL в своем проекте.

pymysql

Самый простой и быстрый способ исправить ошибку — установить библиотеку pymysql:

python3 -m pip install PyMySQL

Что бы вы смогли использовать ее в Django, в файле settings.py вам нужно импортировать библиотеку и использовать метод для подключения к API MySQLdb:

import pymysql
pymysql.install_as_MySQLdb()

Эти настройки может понадобится положить в другие файлы, такие как ‘__init__.py’ или ‘manage.py’. Это зависит от вашего проекта. Суть в том, что мы должны импортировать pymysql до того, как будет выполнен импорт MySQLdb. Обычно это происходит в ‘settings.py’ в DATABASES.

Ниже пример файла настроек, который использую я при локальной разработке:

Подключение библиотеки PyMySql в Django

На странице проекта в github есть уточнение, которое касалось версий Django 2.2+ и следующей ошибкой:

  • django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3;

Я эту ошибку не встречал, но исправить ее можно вручную заменив версию mysqlclient следующим образом:

import pymysql
pymysql.version_info = (1, 4, 6, 'final', 0)
pymysql.install_as_MySQLdb()

Каких либо ошибок при работе с этой библиотекой я не замечал.

mysqlclient

Перед установкой библиотеки mysqclient, в случае Linux, вам понадобится установить целый ряд дополнительных пакетов для компиляции:

# Разработчики указывают следующие пакеты
# Ubuntu
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential

# CentOS
sudo yum install python3-devel mysql-devel

# библиотеки, которые могут понадобится
# (советы с форумов, которые мне не пригодились)
sudo apt-get install mysql-client libssl-dev

В качестве эксперимента я установил чистый Windows 10 и Django 3.2 и ошибок с mysqlclient не было. Возможно разработчики что-то исправили. Если на Windows у вас все равно появляются ошибки, то вы можете скачать скомпилированную версию и установить ее через pip:

python3 -m pip install C:/mysqlclient-1.4.6-cp39-cp39-win32.whl

В случае Windows этот способ у меня не всегда срабатывал. Поэтому я предпочитаю, если использую MySQL, использовать PyMySQL локально, а mysqlclient на сервере.

Далее устанавливаем саму библиотеку через pip:

python3 -m pip install mysqlclient

mysql-connector-python

Эта официальная библиотека от разработчиков Oracle написанная на Python 2.7. Эта библиотека так же поддерживается разработчиками Django. В более новых версиях Django 3+ можно увидеть следующую ошибку:

  • ‘mysql.connector.django’ isn’t an available database backend or couldn’t be imported. Check the above exception. To use one of the built-in backends, use ‘django.db.backends.XXX’, where XXX is one of:  ‘mysql’, ‘oracle’, ‘postgresql’, ‘sqlite3’

В Django 2.2 можно увидеть следующую ошибку:

  • django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?

Эти ошибки связаны с отсутствием поддержки Python 2.7 начиная с Django 2.0. В марте 2020 года (прошел год с написания статьи) разработчики отписывались о том что в курсе этой проблемы и решают ее. Вы можете попытать удачу и установить этот модуль следующим образом:

python3 -m pip install mysql-connector-python

В файле setting.py указать следующие настройки:

DATABASES = {
    'default': {
        'ENGINE': 'mysql.connector.django',
        'NAME': ,
        'USER': ,
        'PASSWORD': ,
        'HOST': ,
    }
}

Теги:

#python

#django

How to use mySqlclient

To use this service, you have to install it through the Python package installer pip, as shown below:

pip install mysqlclient

This command will automatically download and install the mysqlclient package into your device. However, this process is not always problem-free due to some reasons, like pip trying to install the latest version that might not match properly with your system.
If a problem arises, pip will throw an error with a message like mysqliclient installation error.

I want to install MySQL on my Ubuntu 20.10 desktop, but I’m facing issues.
I tried installing python3-dev and libmysqlclient-dev.

When running:

pip3 install mysqlclient

I keep getting the error below:

pip3 install mysqlclient error

How may I solve this?

BeastOfCaerbannog's user avatar

asked Mar 4, 2021 at 18:33

Shivangi Varshney's user avatar

1

Check this thread, maybe it helps you.

Error installing libmysqlclient-dev on Ubuntu 20.04

Step 0: sudo apt install python3-dev build-essential

Step 1: sudo apt install libssl1.1

Step 2: sudo apt install libssl1.1=1.1.1f-1ubuntu2

Step 3: sudo apt install libssl-dev

Step 4: sudo apt install libmysqlclient-dev

Step 5: pip3 install mysqlclient

That’s it!

ps: To find out these all steps, I was spent almost 4-5 Hours. :D

answered Apr 16, 2021 at 19:35

shivang patel's user avatar

1

As mentioned here you should do:

  • sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
    Debian / Ubuntu
  • sudo yum install python3-devel mysql-devel
    Red Hat / CentOS

After that just do pip install mysqlclient

answered Aug 5, 2021 at 11:40

Josef Frola's user avatar

1

This can usually be resolved with the libffi-dev libraries; libffi.so specifically. It can be installed via apt with:

sudo apt install libffi-dev

Note: I have not found a way to install this via pip3. Do let me know if you find it somewhere.

Once libffi-dev is installed, run ldconfig to load the new .so.

Important: If you compiled your own Python installation, then you will need to recompile it for libffi-dev to be loaded.

answered Mar 4, 2021 at 23:59

If you are having trouble while setting up virtual environment then do mention python version:

sudo apt-get install python3.5-dev

sudo apt-get install mysql-client 

sudo apt-get install libmysqlclient-dev 

sudo apt-get install libssl-dev 

answered Aug 11, 2021 at 11:15

Lakpa Sherpa's user avatar

I am trying to install the mysqlclient Python package (https://pypi.python.org/pypi/mysqlclient) into a virtual Python 2.7 environment on Windows 7 (on a local PC, and on the Appveyor CI) and cannot get it done.

I am describing the issues for the local PC with Win 7, but it happens basically the same way on Appveyor.

Packages in my virtualenv when I start:

pip (9.0.1)
setuptools (36.6.0)
wheel (0.30.0)

pip install mysqlclient initially says:

. . .
running build_ext
building '_mysql' extension
error: Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27

Apparently, Python 2.7 requires VC9. After installing it, pip install mysqlclient gets a little further, but misses include files:

. . .
building '_mysql' extension
creating buildtemp.win-amd64-2.7
creating buildtemp.win-amd64-2.7Release
C:Program Files (x86)Common FilesMicrosoftVisual C++ for Python9.0VCBinamd64cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,3,12,'final',0) -D__version__=1.3.12 "-IC:Program Files (x86)MySQLMySQL Connector C 6.1include" -IC:Python27include -IC:UsersAndivirtualenvsmysqlclientPC /Tc_mysql.c /Fobuildtemp.win-amd64-2.7Release_mysql.obj /Zl
_mysql.c
_mysql.c(29) : fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory
error: command 'C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe' failed with exit status 2

In order to get the header files, I installed the «MySQL Connector/C 6.1.10» from https://downloads.mysql.com/archives/get/file/mysql-connector-c-6.1.10-winx64.msi. This is admittedly only the second latest version, but I need to install it on Appveyor from the command line, and did not find out how to download the latest version in an unattended manner.

Also, using the MSI installer installs the package in C:Program FilesMySQLMySQL Connector C 6.1 but the build step in pip install expects it in C:Program Files (x86)MySQLMySQL Connector C 6.1, so I softlinked it:

mklink /D "C:Program Files (x86)MySQLMySQL Connector C 6.1" "C:Program FilesMySQLMySQL Connector C 6.1"

When looking at the files in that version of the MySQL Connector/C, it has only lib/vs12 and lib/vs14 directories:

lib/vs12/mysqlclient.lib
lib/vs14/mysqlclient.lib

As expected, pip install mysqlclient now gets beyond the compiles, but fails when linking:

. . .
running build_ext
building '_mysql' extension
creating buildtemp.win-amd64-2.7
creating buildtemp.win-amd64-2.7Release
C:Program Files (x86)Common FilesMicrosoftVisual C++ for Python9.0VCBinamd64cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,3,12,'final',0) -D__version__=1.3.12 "-IC:Program Files (x86)MySQLMySQL Connector C 6.1include" -IC:Python27include -IC:UsersAndivirtualenvsmysqlclientPC /Tc_mysql.c /Fobuildtemp.win-amd64-2.7Release_mysql.obj /Zl
_mysql.c
_mysql.c(242) : .... several warnings ...
C:Program Files (x86)Common FilesMicrosoftVisual C++ for Python9.0VCBinamd64link.exe /DLL /nologo /INCREMENTAL:NO "/LIBPATH:C:Program Files (x86)MySQLMySQL Connector C 6.1libvs9" /LIBPATH:C:Python27Libs /LIBPATH:C:UsersAndivirtualenvsmysqlclientlibs /LIBPATH:C:UsersAndivirtualenvsmysqlclientPCbuildamd64 /LIBPATH:C:UsersAndivirtualenvsmysqlclientPCVS9.0amd64 kernel32.lib advapi32.lib wsock32.lib mysqlclient.lib /EXPORT:init_mysql buildtemp.win-amd64-2.7Release_mysql.obj /OUT:buildlib.win-amd64-2.7_mysql.pyd /IMPLIB:buildtemp.win-amd64-2.7Release_mysql.lib /MANIFESTFILE:buildtemp.win-amd64-2.7Release_mysql.pyd.manifest /MANIFEST
LINK : fatal error LNK1181: cannot open input file 'mysqlclient.lib'
error: command 'C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\link.exe' failed with exit status 1181

I did not find a version of the «MySQL Connector/C» package that can still be downloaded and that works with VC9. Using the mysqlclient.lib files in the vs12 or vs14 directories in this vc9 build results in unresolved symbols.

My questions are:

  • What package(s) do I need to use in order to get the right header files (e.g. mysql.h) and libraries (e.g. mysqlclient.lib) for a successful pip install mysqlclient on Windows 7?
  • More generally, what are the prerequisites for a successful pip install mysqlclient on Windows 7?

Понравилась статья? Поделить с друзьями:
  • Ошибка при установке mta province
  • Ошибка при установке msvcrt dll
  • Ошибка при установке msi windows 10
  • Ошибка при установке msi afterburner
  • Ошибка при установке ms sql server 2019