Error no matching distribution found for mysqldb

This post goes over installing the necessary package to work with a MySQL database with Python3. It then demonstrates some simple Create, Retrieve, Update, and Delete (CRUD) example code operations.

MySQL and Python Logos

I’m using Python more and more so it’s not surprising that recently the need arose to connect to and insert into a MySQL database. I was using (and usually do) Python3, and I ran into a couple of issues in the begining. This post will document those issues and the solutions I found to get MySQL and Python3 to work together.

Package Installation

Support for MySQL doesn’t ship with the Python installer, therefore we need to install a package that adds this functionality. I usually use pip3 for this task, and I tried the following.

pip3 install MySQLdb

I found code examples online showing import MySQLdb statements, so I figured that was the name of the package. I was wrong.

Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb

So I thought, let’s try just pip3 install mysql

Collecting mysql
  Using cached https://files.pythonhosted.org/packages/06/ef/c4efbf2a51fb46aba9be03a973638d9539c9ca10a5259b2cbb1a66133b2e/mysql-0.0.1.tar.gz
Collecting MySQL-python (from mysql)
  Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip
Installing collected packages: MySQL-python, mysql
  Running setup.py install for MySQL-python ... error
    Complete output from command "c:program filespython36python.exe" -u -c "import setuptools, tokenize;__file__='C:\Users\admin\AppData\Local\Temp\pip-install-88jce1si\MySQL-python\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:UsersadminAppDataLocalTemppip-record-f7l848e_install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
[omitted output]
    building '_mysql' extension
    creating buildtemp.win-amd64-3.6
    creating buildtemp.win-amd64-3.6Release
    C:Program Files (x86)Microsoft Visual Studio2017CommunityVCToolsMSVC14.12.25827binHostX64x64cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:Program Files (x86)MySQLMySQL Connector C 6.0.2include" "-Ic:program filespython36include" "-Ic:program filespython36include" "-IC:Program Files (x86)Microsoft Visual Studio2017CommunityVCToolsMSVC14.12.25827Include" "-IC:Program Files (x86)Windows Kits10include10.0.16299.0shared" "-IC:Program Files (x86)Windows Kits10include10.0.16299.0um" "-IC:Program Files (x86)Windows Kits10include10.0.16299.0winrt" "-IC:Program Files (x86)Windows Kits10include10.0.16299.0ucrt" "-IC:Program Files (x86)Windows KitsNETFXSDK4.6.1includeum" /Tc_mysql.c /Fobuildtemp.win-amd64-3.6Release_mysql.obj /Zl
    _mysql.c
    _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
    error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\bin\HostX64\x64\cl.exe' failed with exit status 2

Okay this is more like it, but now I’m receiving an error instead of installing a package.

The Python MySQL cl.exe Distraction

Searching the error error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\bin\HostX64\x64\cl.exe' failed with exit status 2 and I learned that cl.exe is the Visual C++ compiler.

Apparently, the installation of the compiler is done via Visual Studio. I have Visual Studio installed so I loaded up the Visual Studio Installer – the program used to add functionality to VS. Sure enough, I didn’t have the Visual C++ components installed. I started installing it. It was taking awhile because the installation size was over 1 GB. While that was going on I continued to research MySQL and Python3. Before the process finished, I learned that the MySQLdb was not designed for Python3; the functionality was replaced by the mysqlclient package.

The Right Package (mysqlclient)

Now knowing that MySQLdb was out and mysqlclient was in, I went ahead and installed that package.

pip3 install mysqlclient
Collecting mysqlclient
  Using cached https://files.pythonhosted.org/packages/32/4b/a675941221b6e796efbb48c80a746b7e6fdf7a51757e8051a0bf32114471/mysqlclient-1.3.12-cp36-cp36m-win_amd64.whl
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.12

Example CRUD Operations

Now that the right MySQL package is installed, let’s do some basic Create, Read, Update, and Delete (CRUD) operations.

Create

The following example opens a CSV file containing records of gold PRICE on a given day (TIMESTAMP) from a given SOURCE.

import MySQLdb as mdb

PRICE     = 0
TIMESTAMP = 1
SOURCE    = 2

conn = mdb.connect('hostname', 'username', 'p@s$w0rd', 'database')
cursor = conn.cursor()

with open('gold_price.csv', 'r') as gold_prices:
    lines = gold_prices.read().splitlines()

    for i in range(1, len(lines)):
        _tuple = lines[i].split(',')
        cursor.execute("INSERT INTO gold_price (price, time, source) VALUES (%s, '%s', '%s');" %
        (_tuple[PRICE], _tuple[TIMESTAMP], _tuple[SOURCE]))

cursor.close()
conn.commit()
conn.close()

Retrieve

This bit fetches all the rows in a table (i.e. gold_price) and prints out each row – as a tuple.

import MySQLdb as mdb

conn = mdb.connect('www.jasonfavrod.com', 'econ', 'i8peanut$', 'econ')
cursor = conn.cursor()

cursor.execute('SELECT * FROM gold_price;')

for row in cursor.fetchall():
    print(row)

cursor.close()
conn.close()
# Output
(1319.03, 'https://www.xe.com/currencyconverter/convert/?Amount=1&From=XAU&To=USD', datetime.datetime(2018, 5, 12, 19, 30, 2))
(1313.33, 'https://www.xe.com/currencyconverter/convert/?Amount=1&From=XAU&To=USD', datetime.datetime(2018, 5, 14, 21, 0, 3))
(1290.68, 'https://www.xe.com/currencyconverter/convert/?Amount=1&From=XAU&To=USD', datetime.datetime(2018, 5, 15, 21, 0, 3))
[output omited]

Update

Here I’ll update the gold price on a give date to $1300.

import MySQLdb as mdb

conn = mdb.connect('www.jasonfavrod.com', 'econ', 'i8peanut$', 'econ')
cursor = conn.cursor()

cursor.execute("UPDATE gold_price SET price = %s WHERE time = %s", ("1300", "2018.05.15-21:00:03"))
cursor.close()
conn.commit()
conn.close()

Delete

Now we can delete that altered entry.

import MySQLdb as mdb

conn = mdb.connect('www.jasonfavrod.com', 'econ', 'i8peanut$', 'econ')
cursor = conn.cursor()


cursor.execute("DELETE from gold_price WHERE time = '%s'" % "2018-05-23 02:56:07")
cursor.close()
conn.commit()
conn.close()

For more on the mysqlclient for Python3, see their Github project.

#mysql-python

#mysql-python

Вопрос:

Я хочу установить MySQLdb без использования Conda

Я уже сделал это https://ruddra.com/install-mysqlclient-macos / и успешно установлен на мой mac:

  - MySQL
 - mysqlclient
 - mysql-connector-c
 

Моя конечная цель — импортировать MySQLdb в jypiter notebook и подключиться для записи данных в базу данных mysql.

Может кто-нибудь, пожалуйста, дать мне пошаговое решение, что делать дальше, как заставить его работать?

У меня есть MAC OS Mojave 10.14.5 / Python 3.9

когда я делаю

 pip install Mysqldb
 

я получаю сообщение об ошибке

 ERROR: Could not find a version that satisfies the requirement MySQLdb
ERROR: No matching distribution found for MySQLdb
 

когда я делаю

 pip install MySQL-python
 

я получаю другую ошибку:

 WARNING: Discarding https://files.pythonhosted.org/packages/9a/81/924d6799494cf7fb24370335c2f782088d6ac4f79e4137d4df94cea3582c/MySQL-python-1.2.3.tar.gz#sha256=7de66fbbf923634e7c965aeaefa74642ba75ae20ee1cefcefc3009595b7a7e6e (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement MySQL-python
ERROR: No matching distribution found for MySQL-python
 

Комментарии:

1. Какие «разные способы» вы пытались установить? Вам нужно объяснить, что вы делаете, чтобы получить эту ошибку, чтобы у вопроса был шанс быть по теме. Это может быть не по теме для SO, потому что на самом деле это не о программировании, но это определенно не по теме, если просто запрашивать руководства / примеры.

2. У вас уже есть mysqlclient, который можно использовать для подключения к MySQL из Jupyter notebook

Ответ №1:

Оказалось, что для Python3.x все отлично работает с PyMySQL 🙂

Я сделал

 !python3 -m pip install PyMySQL
 

и

 pymysql.connect(host = '....', 
                user = '....', 
                password = '....', 
                database = '....')
 

Sometimes you get an error when you’re trying to install a Python package
using pip. It looks like this:

Could not find a version that satisfies the requirement (from versions:)
No matching distribution found for

Some probable reasons for this error are:

  1. PyPI server isn’t responding to your requests. It can happen either because
    the PyPI server is down or because it has blacklisted your IP address. This
    happened to me once when I was trying installing packages on a server.
    This can be fixed by using a proxy with pip. See the solution below.

  2. You’re running an older pip (especially on Mac). This can be fixed by
    upgrading your pip.
    See this post on Stack Overflow.
    Thanks to Anupam Jain who pointed this in a comment.

  3. The package you’re trying to install is not available for your Python version.

  4. The package is not available for your operating system. This is a rare case
    and only happens when the package is not pure-Python, i.e. it’s been
    partially written in C or Cython. Such a package needs to be compiled for
    every operating system (Windows/Mac/Linux) and architecture (32-bit/64-bit).
    Suppose a package has only been compiled for Windows 64-bit, then you’ll get
    this error if you try to install it on Windows 32-bit, or any other
    OS.

  5. The package is not present on PyPI server. In this case pip will not work. So
    you’ll have to download and install the package manually from Github or wherever
    it is available.

Solution¶

I had this issue because PyPI server had blacklisted the IP
of my hosting provider, the obvious solution was to make pip install via a proxy.

But to see if that’s also the case with you, you can test it like this:

$ curl https://pypi.org

The requestors Network has been blacklisted due to excessive request volume. 
If you are a hosting customer, please contact your hosting company's support. 
If you are the hosting company, please contact infrastructure-staff@python.org to resolve

If you see the message similar to above, that means your IP has also been
blacklisted by https://pypi.org.

If you don’t see this message then the reason for the pip error could be that you’re using
an older version. See this post on Stack Overflow
for a solution.

Anyways, this can be fixed by using a proxy with pip.

Supplying a proxy address to pip is easy:

$ pip install -r requirements.txt --proxy address:port

Above, address and port are IP address and port of the proxy.

To find proxies, just search Google for proxy list.

Other things that I tried¶

These are some other things that I tried to get rid of this issue.
Although they didn’t work for me, but they might work for you.

  1. Changing DNS resolver of my server.
    This makes sense if your server’s DNS resolver can’t find PyPI servers.
  2. Reconfiguring SSL, reinstalling CA certificates.
    This makes sense if you don’t have updated CA certificates which are used by
    PyPI servers.
  3. Downloading packages using wget.
    This is an alternative way to install Python packages. Download them via wget
    and then install them using python setup.py install. In my case, the server was
    blacklisted by PyPI so I was getting a 403 Forbidden error.
  4. Downloading packages using curl.
    Alternative to wget. In my case I didn’t get a 403 error but rather it just
    created invalid tarball files, instead of actually downloading them.
  5. Downloading packages using git or hg.
    If your desired packages have git or hg repositories that you can clone, this
    is a good workaround.

Понравилась статья? Поделить с друзьями:
  • Error no matching distribution found for matplotlib
  • Error no match for operator operand types are std ostream
  • Error no valid items were selected must be joints effectors or nurbs curves
  • Error no main class specified intellij idea kotlin
  • Error no ups definitions found in ups conf