Installing the MySQLdb Python module on Snow Leopard

Needing to access a MySQL database through Python, I was faced by the inability to easily install the MySQLdb module. I do use MacPorts, but after running the obvious
sudo port install py26-mysql
I realized that I would be downloading, compiling and installing a new instance of Python, a new instance of MySQL (I prefer the simplicity of MAMP), and who knows what else.

Installing the module alone doesn’t work, because MAMP installs no headers; and copying the headers from the vanilla MySQL distribution doesn’t help either, because a few of the required files are generated on the fly during the installation of MySQL itself.

The solution, it turns out, is relatively simple. Follow along.

Step 1: download the latest MySQL Community Server in DMG format for x86-64 from this page, and install the main package. Worry not: nothing is going to be started on boot, so this is not going to mess with your pre-existing MySQL installation. The package is going to be installed in /usr/local/mysql-5.1.45-osx10.6-x86_64/, with a handy /usr/local/mysql/ symbolic link.

Step 2: download the latest MySQLdb Python module from this page, and unpack it somewhere.

Step 3: set the $PATH environment variable to include /usr/local/mysql. That’s because the module’s is going to need to call mysql_config, and you want it to find the one you just installed, as it comes with all the stuff it needs.

Step 4: do the classic build and install dance, making sure you prepend the commands with ARCHFLAGS=’-arch x86_64′. This is because you want to compile a 64-bit module.

In short:
tar vxfz MySQL-python-1.2.3c1.tar.gz
cd MySQL-python-1.2.3c1
export PATH=/usr/local/mysql:$PATH
ARCHFLAGS='-arch x86_64' python build
ARCHFLAGS='-arch x86_64' python install

If all went fine, you should be able to do this without getting any errors:
octavarium:~ jollino$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> print MySQLdb
<module 'MySQLdb' from '/Library/Python/2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg/MySQLdb/__init__.pyc'>


Before you go…

Did you enjoy reading this post without ads?
If so, you may consider supporting this blog through Ko-fi!

3 thoughts on “Installing the MySQLdb Python module on Snow Leopard

  1. You could do same by setting the path of MySQL installed by MAMP? No?

Comments are closed.