Thursday, June 6, 2013

python connection with mysql DB and data fetch on Linux(Ubuntu)


At first check the installation of python by firing this command on console


>$mysql -h 127.0.0.1 -u root -p
 password: *******

PS:Here my installation of mysqldb is as a root user which is true in most of the cases as mysql come pre packaged with ubuntu 12 , (i am not sure about the earlier versions but u can always test it by firring a simple command  which mysql  and figure out if you have already mysql installed)

an empty result ensures that you do not have mysql installed where as the result pointing to a bin location represents that you already  have mysql.

Any way there are millions of web pages already available on how  to install mysql on ubuntu so i will not get on to it and try to stick to the blog headline which is connection of python script to mysql db to fetch data. (U also need to worry about python installation if it is not part of distribution of linux package you are using.
  
any way : 

I assume now you have a working mysql and have created a DB and a basic table with some data in it
(create simple table with one id and one data column to keep it simple)

Now 
save this script as a python script

mport MySQLdb

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

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

# Use all the SQL you like
cur.execute("SELECT * FROM NODEJSTEST")

# print all the first cell of all the rows
for row in cur.fetchall() :
    print row[0]

This should be able to return you all the columns from your table 

Error:             if you get in to error of mysqldb not recognised

sudo apt-get install python-mysqldb

Running this will get you out of this error . Some time it appears some time it does not hence i have not included it as a part of regular work. It is also possible that the system it worked , was already configured for it (i work on dev set up which is used by many developers so can not really tell ), so may be its a necessary step. You might want to even do it as a regulr step if you dislike errors :) 

Mail me if you do not find the steps working and we shall work together to get it working