Tuesday, 17 August 2010

Installing MySQLdb python module

MySQLdb is a Python wrapper around _mysql written by Andy Dustman. This wrapper makes it possible to interact with a MySQL Server performing all sorts of DDL and DML statements. I began my Python journey recently and stumbled at the installation of the MySQLdb module install. I was keen not to jump at an apt/yum installation as we have servers that have no outbound connections I decided I wanted to build the module from source.

You can download the MySQLdb files from SourceForge (70kb)

When downloaded you need to prep before your system is ready to build the file. Here are some prerequisites that will make life easier for you. I performed this particular install using an Ubuntu 10.04 64bit OS.

Before you start ensure you have the following installed (MySQL isn't actually required but for local Python development it's nice to have a database server to develop against!)
  • MySQL Server. I used the MySQL Community Server Version 5.1.49
  • gcc - The GNU Compiler Collections
My first attempt at a build resulted in the following error message

$> tar -xzvf MySQL-python-1.2.3.tar.gz
$> cd MySQL-python-1.2.3
$> python setup.py build

Traceback (most recent call last):
  File "setup.py", line 5, in
    from setuptools import setup, Extension
ImportError: No module named setuptools

This was resolved by installing another Python module namely 'python-setuptools' (I did take the short cut here using apt-get). I later found out that python-dev and libmysqlclient15-dev were more packages that I needed for the build so I'm tagging them on here.

$> sudo apt-get install python-setuptools python-dev libmysqlclient15-dev

With this installed I decided I was ready to build again but again another splurge of error code and this time my system was complaining about 'mysql_config' (you might not incur this issue after the previous apt-get installs but I'm including it anyway just in case you see this message.)

EnvironmentError: mysql_config not found

I updated my PATH environment variable and I was ready to try again...

$> export PATH=$PATH:/usr/local/mysql/bin

You should be ready (properly ready this time!) to build and install your MySQLdb wrapper

$> sudo python setup.py build
{various output}

$> sudo python setup.py install
{...Installed /usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-x86_64.egg}

Now open your python command line and import the new MySQLdb module

>>> import MySQLdb