Belle
Belle

Reputation: 451

ModuleNotFoundError: No module named 'MySQLdb'

After finishing of one of my Flask projects, I uploaded it on github just like everybody else. after a 2-3 months period I downloaded the entire githube repository on another machine to run it. However, the app is not working because the packages are not found giving the following message

ModuleNotFoundError: No module named 'Flask'

So I ended up downloading all packages starting from Flask, SQLalchemy,..etc! but I got stuck with MySQLdb:

(MYAPPENV) C:\Users\hp\myapp>python run.py
Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from app import app
  File "C:\Users\hp\myapp\app\__init__.py", line 4, in <module>
    from instance.config import engine
  File "C:\Users\hp\myapp\instance\config.py", line 52, in <module>
    engine = create_engine("mysql://root:root@localhost/MYAPPDB")
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\__init__.py", line 425, in create_engine
return strategy.create(*args, **kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\strategies.py", line 81, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.py", line 102, in dbapi
    return __import__('MySQLdb')
ModuleNotFoundError: No module named 'MySQLdb'

Could anybody please help with this issue? I am using python37 on windows machine. I even tried downloading packages such as mysqlclient,..etc but it didn't work out.

Upvotes: 26

Views: 84738

Answers (8)

Rich Lysakowski PhD
Rich Lysakowski PhD

Reputation: 3095

I got the following error when trying to install MySQLdb on Windows 10. I downloaded MySQL from the Oracle website, and then the MySQL Connector Python 8.0.30. I got this horrible message from the Oracle MySQL installer:

Oracle Heavy Handed Installer Error Message

sqlalchemy\dialects\mysql\mysqldb.py", line 163, in dbapi return import("MySQLdb")

ModuleNotFoundError: No module named 'MySQLdb'

I used this command to find the right conda package:

conda search mysql-connector

Then I used the following conda command to install the mysql-connector-python package.

conda install -c conda-forge mysql-connector-python

The conda command above gave me this result:

Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: c:\ProgramData\Anaconda3\envs\topss

  added / updated specs:
    - mysql-connector-python


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    dnspython-2.2.1            |     pyhd8ed1ab_0         136 KB  conda-forge
    mysql-common-8.0.31        |       hd2cd81a_0         1.9 MB  conda-forge
    mysql-connector-python-8.0.28|   py38h085e425_0         585 KB  conda-forge
    mysql-libs-8.0.31          |       h4d1747d_0         1.9 MB  conda-forge
    ------------------------------------------------------------
                                           Total:         4.5 MB

The following NEW packages will be INSTALLED:

  dnspython          conda-forge/noarch::dnspython-2.2.1-pyhd8ed1ab_0 None
  mysql-common       conda-forge/win-64::mysql-common-8.0.31-hd2cd81a_0 None
  mysql-connector-p~ conda-forge/win-64::mysql-connector-python-8.0.28-py38h085e425_0 None
  mysql-libs         conda-forge/win-64::mysql-libs-8.0.31-h4d1747d_0 None


Proceed ([y]/n)? y


Downloading and Extracting Packages
mysql-connector-pyth | 585 KB    | ################################################################################################################## | 100%  
dnspython-2.2.1      | 136 KB    | ################################################################################################################## | 100%  
mysql-common-8.0.31  | 1.9 MB    | ################################################################################################################## | 100%  
mysql-libs-8.0.31    | 1.9 MB    | ################################################################################################################## | 100%  
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
Retrieving notices: ...working... done

So everything worked.

Upvotes: 0

Kaan Ateşel
Kaan Ateşel

Reputation: 470

You should first install python3-dev, default-libmysqlclient-dev, build-essential then you can install mysqlclient.

For Red Hat

sudo yum install python3-devel mysql-devel
pip install mysqlclient

For Debian

sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
pip install mysqlclient

Upvotes: 4

luciela
luciela

Reputation: 75

Hello internet people,

I reach this page because of the same problem.
But I'm using Ubuntu 18.04 and Python 3.6

Python snippet - app.py

from flask import Flask, render_template
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'YourHost' 
app.config['MYSQL_USER'] = 'YourUserName'
app.config['MYSQL_PASSWORD'] = 'UserPassword'
app.config['MYSQL_DB'] = 'TheDbName'
mysql = MySQL(app)

app.secret_key = 'YourUltimateSuperSecretKey'

@app.route('/')
@app.route('/index')
def index():
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM users')
    data = cur.fetchall()
    cur.close()
    return render_template('index.html', test = data)

if __name__ == "__main__":
    app.run(debug=True)

HTML - index.html

<div>
    {% for x in test %}
        {{ x }}
    {% endfor %}
</div>

So this is what i did to solve the problem:
First I installed the missing package:

sudo apt install python3-mysqldb

After that I installed those libraries with pip on the environment:

pip install Flask-MySQLdb mysql-connector-python

and it worked :)

Upvotes: 6

Espoir Murhabazi
Espoir Murhabazi

Reputation: 6376

I have read that mysqldb is not supported by python3

And it looks like when you are trying to connect to your database you are using mysql db to connect to the database by default!

you need to change it by editing your DATABASE_URI configuration

But before you need to install the connector extension :

with this command :

pip install mysql-connector-python

And according to this documentation you can edit your DATABASE_URI and change the default connector like this :

DATABSE_URI='mysql+mysqlconnector://{user}:{password}@{server}/{database}'.format(user='your_user', password='password', server='localhost', database='dname')

I hope this will help...

Upvotes: 61

Tri
Tri

Reputation: 3039

You can install mysqlclient with pip

If using Python3, try this:

pip3 install mysqlclient

or in Python2

pip install mysqlclient

Upvotes: 22

aether
aether

Reputation: 21

I have the same problem like you. Here is my solution:

Reason: python3.X does not support MySQLdb,so you need to change to pymysql model

Solution: Change the content of import.

1):

replace all MySQLdb with pymysql

2):

def reconnect(self):
    """Closes the existing database connection and re-opens it."""
    self.close()
    self._db = pymysql.connect(**self._db_args)# MySQLdb.connect(**self._db_args)
    self._db.autocommit(True)

3)

if pymysql is not None:
    # Fix the access conversions to properly recognize unicode/binary
    FIELD_TYPE = pymysql.connections.FIELD_TYPE # MySQLdb.constants.FIELD_TYPE
    FLAG = pymysql.constants.FLAG# MySQLdb.constants.FLAG
    CONVERSIONS = copy.copy (pymysql.converters.conversions)# (MySQLdb.converters.conversions)

    field_types = [FIELD_TYPE.BLOB, FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING]
    if 'VARCHAR' in vars(FIELD_TYPE):
        field_types.append(FIELD_TYPE.VARCHAR)

    for field_type in field_types:
        # CONVERSIONS[field_type] = [(FLAG.BINARY, str)] + CONVERSIONS[field_type]
        CONVERSIONS[field_type] = [(FLAG.BINARY, str)].append(CONVERSIONS[field_type])

    # Alias some common MySQL exceptions
    IntegrityError = pymysql.IntegrityError# MySQLdb.IntegrityError
    OperationalError = pymysql.OperationalError# MySQLdb.OperationalError

4):

def __init__(self, host, database, user=None, password=None,
                 max_idle_time=7 * 3600, connect_timeout=10,# 设置连接超时时间,时间是秒
                 time_zone="+0:00", charset = "utf8", sql_mode="TRADITIONAL"):

5):

def query(self, query, *parameters, **kwparameters):
    """Returns a row list for the given query and parameters."""
    cursor = self._cursor()
    try:
        self._execute(cursor, query, parameters, kwparameters)
        column_names = [d[0] for d in cursor.description]
        return [Row(itertools.zip_longest(column_names, row)) for row in cursor]
    finally:
        cursor.close()

Upvotes: 2

current_liu
current_liu

Reputation: 81

import pymysql
pymysql.install_as_MySQLdb()

Upvotes: 8

Learning is a mess
Learning is a mess

Reputation: 8277

To install MySQLdb, provided pip or pip3 is installed on your machine:

pip install mysqlclient

Upvotes: 13

Related Questions