Thursday 19 December 2013

Connect to MySQL database and retrieve data in python

I have implemented this program which will connect to Mysql and retrieve all the database, tables and containing data. we can read all column row data from this program.

for retrieving the MYSQL server data 1st we have to install one library which is mysqldb  library. Download this library from here Download.

Through this library, it will connect to Mysql server by hostname, username, password and fetch all data like database, tables and tables data.


import re
import MySQLdb

db = MySQLdb.connect("localhost","root","root@123")
cur = db.cursor() 
cur.execute("show databases")
for ro in cur.fetchall() :
    cur.execute("use "+ro[0])
    cur.execute("show tables")
    for rem in cur.fetchall() :
        cur.execute("select * from "+rem[0])
        for row in cur.fetchall():
            for x in range(0,len(row)):
                data=str(row[x])

db.close()

This username & password are MySQL credentials
If you want to connect remote MySQL then you have to use below code for it. it will connect through ip address.
import re
import MySQLdb

db = MySQLdb.connect("\\\\192.168.1.18","root","root@123")
cur = db.cursor() 
cur.execute("show databases")
for ro in cur.fetchall() :
    cur.execute("use "+ro[0])
    cur.execute("show tables")
    for rem in cur.fetchall() :
        cur.execute("select * from "+rem[0])
        for row in cur.fetchall():
            for x in range(0,len(row)):
                data=str(row[x])

db.close()
try it, Thanks guys.

No comments:

Post a Comment