Solving Library not loaded: libmysqlclient.18.dylib when importing MySQLdb on Lion

If you’ve installed OS X lion and install mysql from the oracle .pkg, you’ll find that you get an error when you try and use python’s MySQL package.

TESTBOX:~ admin$ python
Python 2.7.3 (default, Aug 23 2012, 15:13:32) 
[GCC 4.2.1 Compatible Apple Clang 4.0 ((tags/Apple/clang-421.0.60))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
  File "", line 1, in 
  File "/Library/Python/2.7/site-packages/MySQLdb/__init__.py", line 19, in 
    import _mysql
ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Library/Python/2.7/site-packages/_mysql.so
  Reason: image not found
>>> exit()

This error is a a result of the MySQLdb module looking for one of MySQLs library in the wrong place. The .pkg installer from Oracle appears not to install links to some of the libraries correctly. Luckily the fix is easy.

sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Python/2.7/site-packages/_mysql.so

In short, this makes this particular library available when the _mysql.so file calls it. If the error from python (above) says that it was “Referenced from:” a different file, use that filename as the last parameter in the above command. For instance:

sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Directories/To/File/filereferencedinpython

Now normally you’d use something like:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/

to achieve the same thing, however I can’t seem to get my .bash_profile to work on this machine!

4 thoughts on “Solving Library not loaded: libmysqlclient.18.dylib when importing MySQLdb on Lion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s