Sunday, January 26, 2014

MySQL database access using Python in Raspberry Pi

          While working with Python in Raspberry Pi it might be useful to have a database access for your application or somewher it is required.Or may be as a beginner you would like to use MySQL with Python.Here i have compiled a post on how to use MySQL with Python...
   
            First of all you have to install python-MySQLdb which interacts between the My-SQL database and the Python.So to install it in the Raspberry-Pi terminal type..

          sudo apt-get install python-mysqldb


I have already installed so my screenshot is looking like this..after installing this nothing else is required..

Move to the desktop and open the Python IDLE.Remember don't open the IDLE 3 as it doesn't supports the MySQLdb.


Now in the prompt type
          
 import MySQLdb

if it shows some error then the MySQLdb is not installed.If it is installed then it will show nothing.In the IDLE click on File and New Window this will open a new editor to write the python codes.
Editor...

Now lets you have a database dbase and user is root and PWD is pwd and has a table tab and some stored data.Here is my database snap...


          Now in the editor write the following code and save it by pressing ctrl+s and execute it by pressing F5.It will show you the results in the IDLE shell.

Code:

import MySQLdb=MySQLdb.connect("localhost","user","password","database")
curs=db.cursor()
#tab is a table in the database 
curs.execute("SELECT * FROM tab")
for reading in curs.fetchall():
   print str(reading [0])
db.close()