"Can't initialize character set utf8mb4" with Windows mysql-python
<p>I'm getting an error try to connect to a remote mysql database from a
Windows 7 client via <strong>python 2.7</strong> + <strong>MySQLdb 1.2.5</strong> + <strong>sqlalchemy 1.0.9</strong>. This is a result of recently changing the server's default character set to <strong>utf8mb4</strong>. The server is running <strong>MySQL 5.5.50</strong>.</p>

<p>I connect like this:</p>

<pre><code>DB_ENGINE = sqlalchemy.create_engine("mysql+mysqldb://{user}:{pass}@{host}:{port}/{database}?charset=utf8mb4".format(**DB_SETTINGS))
Session = sqlalchemy.orm.sessionmaker(bind=DB_ENGINE)
</code></pre>

<p>The error is:</p>

<pre><code>  File "C:\Applications\Python27\lib\site-packages\sqlalchemy\engine\default.py", line 385, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "C:\Applications\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "C:\Applications\Python27\lib\site-packages\MySQLdb\connections.py", line 221, in __init__
    self.set_character_set(charset)
  File "C:\Applications\Python27\lib\site-packages\MySQLdb\connections.py", line 312, in set_character_set
    super(Connection, self).set_character_set(charset)
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2019, "Can't initialize character set utf8mb4 (path: C:\\mysql\\\\share\\charsets\\)")
</code></pre>

<p>The server's my.cnf contains the following:</p>

<pre><code>init_connect                   = 'SET collation_connection = utf8mb4_unicode_ci'
init_connect                   = 'SET NAMES utf8mb4'
character-set-server           = utf8mb4
collation-server               = utf8mb4_unicode_ci
skip-character-set-client-handshake
</code></pre>

<p>I have no problem connecting to the database from an Ubuntu client, so I suspect the problem is with the Windows client and not the server's configuration.</p>

<p>The MySQL documentation suggests the error message could be due to the client being compiled without multibyte character set support:</p>

<p><a href="http://dev.mysql.com/doc/refman/5.7/en/cannot-initialize-character-set.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.7/en/cannot-initialize-character-set.html</a></p>

<p>However, as this is Windows I'm simply downloading the client and don't have control over its compilation flags.</p>

<p>I've tried installing MySQLdb in a variety of ways:</p>

<ul>
<li>Downloading and installing the MySQL Connector/Python .msi from dev.mysql.com</li>
<li>Downloading and installing the MySQLdb 1.2.5 .exe from pypi</li>
<li>Running "pip install mysql-python" from the Windows command prompt</li>
</ul>

<p>Each of these results in a MySQLdb library that can't seem to handle the utf8mb4 character set.</p>

<p>Any help would be much appreciated!</p>