I ran into a problem this week when the perl libraries for accessing MySQL databases refused to work on Mac OS X Lion. I did a ‘regular’ install:

  1. Install the 64bit version of MySQL Community Server (being sure to use the .dmg version so as to get the .pkg installer)
  2. use CPAN to install the needed database libraries:
    1. $ perl -MCPAN -e shell
    2. cpan[1]> install Bundle::DBI
    3. cpan[1]> install DBD::mysql

There were no errors during the install, so I assumed all we well, until I tried to actually use the libraries to access a database that is! Using DBI to try connect to a MySQL database gave the following error:

install_driver(mysql) failed: Can't load '/Library/Perl/5.12/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle' for module DBD::mysql: dlopen(/Library/Perl/5.12/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle, 1): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Library/Perl/5.12/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle
  Reason: image not found at /System/Library/Perl/5.12/darwin-thread-multi-2level/DynaLoader.pm line 204.

After a lot of googling I found plenty of people with the same problems, including people on Snow Leopard, so I figured this was not a new problem. I tried a number of the suggested solutions, and most did not work, but after two days of trying, I found one that did, and it was wonderfully simple!

The problem is that the MySQL libraries are not in the OS’s library path, so they are not being found, most of the proposed solutions tried to tackle the problem at compile time, or to use simlinks to hack the libraries into the path, but like I say, these solutions didn’t work for me. What did work is simply updating the library path in my environment!

If you run the command below before executing your Perl script the library is found and all is well!

export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$DYLD_LIBRARY_PATH"

It’s a little awkward to do this all the time, so I added the line to my ~/.bash_profile file, and now it just works for me!

I spent two frustrating days trying to fix this, so hopefully I’ll save others some time by sharing my solution.