Wednesday 28 May 2014

python for mysql

# You might need the following module to be installed in the system:
MySQL-python

So you can try using " sudo pip install MySQL-python " or " sudo easy-install MySQL-python"

if you are getting error while installing MySQL-python [ apt-get install python-mysqldb ]

#!/usr/bin/env python
import MySQLdb

db = MySQLdb.connect(host="hostname", # your host, usually localhost
                     user="username", # your username
                      passwd="password", # your password
                      db="database") # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("select * from Country where Code2 = 'IN';")

# print all the first cell of all the rows
for row in cur.fetchall() :
#    print row[0]
    rows = row   
    print(type(rows))  
    MyList=list(rows)
    print(type(MyList))
    print('Following is in tuple format')
    print(rows)
    print('Following is the list format')
    print(MyList)
#    print row


############ There are other module for connecting the mysql, with different classes." ####

mysql-connector-python


you can try, in python prompt:

>>> dir(MySQLdb) ## to see the modules classes.

## to see installed python module: ## pip list


external link:
http://mysql-python.sourceforge.net/MySQLdb.html

No comments:

Post a Comment