Thursday, April 5, 2012

Install Mysql-Python

In order to connect to Mysql from Python, I used MySQLdb library. It is an interface to the MySQL database server for Python.  For more information -

I installed MySQL-python in my environment following the steps below. 

Import  setuptools:

setuptools is a python package that is used to download, build, install, upgrade, and uninstall Python packages -- easily!  For more information -

And as setuptools was not installed in my machine, I had to make it at first. 

wget  \
sh setuptools-0.6c11-py2.7.egg

Install MySQL-python:

tar -zxvf  MySQL-python-1.2.3.tar.gz
cd  MySQL-python-1.2.3
python build 
python install

Check Installation:

# python
Python 2.7.1 (r271:86832, Jun  8 2011, 12:30:16)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>import MySQLdb

First Script:


#!/usr/bin/python -tt

import MySQLdb as mdb
import sys
con = None
def main():

    con = mdb.connect(host='localhost',  user='testuser',passwd=t'test_passwd',db='testdb',port=3306)
    cur = con.cursor()
    cur.execute("SELECT VERSION()")
    data = cur.fetchone()
    print "Database version : %s " % data
if __name__ == '__main__':

Execute Script:

Database version : 5.1.48-community-log 

For more basics of Mysql programming with Python, you may visit

Leave a Reply