Home > python > How to Connect MySQL with Python

How to Connect MySQL with Python


Since today morning I was trying to get the database connection for my testing python program.But it was very time consuming thing for me to find a proper python support module to connect the DB and after some times I was wondering that such a popular programming language dose not have a fast and easy connecting module for the popular DB like MySQL.

Then I ask my friendly and kind teacher Google Smile how to connect MySQL in python.Oh my kind teacher how sweet he is an how poor his page rank Algorithm he gives me a bunch of links but unfortunately first 5 links can not do the job for me.Smile .Then I change the query 2 or 3 times I found a link http://www.codegood.com/downloads?dl_cat=2  I and got the module installed(for python 2.7 windows 32 bit version) in my W7 but the import statement on the eclipse python editor still got red mark.Sad smile.

Never give up that’s the sprite of a Software Engineer.Smile.So do I.Return to Google my poor friend.After some time I have found link http://www.lfd.uci.edu/~gohlke/pythonlibs/ call Unofficial Windows Binaries for Python Extension Packages .

That is why they say “Never give up” thanks to the maintainers of that super bunch of links.I got the MySQL-python-1.2.3.win32-py2.7.‌exe  [1.0 MB]  [Python 2.7]  [32 bit]  [Sep 01, 2010] I works for me.

This is the script for connecting MySQL with python I have finally done it.Smile.

Created on Jun 8, 2011

@author: kalpa
import MySQLdb

class MyClass(object):

    def __init__(self):

        self.conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db = "tankmap")
        cursor = self.conn.cursor ()
        cursor.execute ("SELECT tankName from tanks")
        names = [f[0] for f in cursor.description]
        for row in cursor.fetchall():
            for pair in zip(names, row):
                print ('%s: %s' % pair)
        cursor.close ()
        self.conn.close ()

foo = MyClass()

I you want to test the code you can download the sql script I had use for this.from here.


Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: