Wednesday, June 8, 2011

How to Connect MySQL with Python

Hi,

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)

                print

        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.

Thanks.

No comments:

Post a Comment