Monday, January 20, 2014

Remote Database Access and Query

Extracting Data from Remote MySQL Database to Local Database


def query_remote_database(request):
     get_all_query = "SELECT * FROM persons"
        try:
            con = MySQLdb.connect(db='remoteDBname', host='192.***.***.***', user='remoteUsername', passwd='mypassword')
            cursor = con.cursor(MySQLdb.cursors.DictCursor)
            cursor.execute(get_all_query)
            datarows_tuple = cursor.fetchall()
            for row in datarows_tuple:
                process_row()
            con.close()
        except Exception as e:
            print "Error:", e


Establish connection using required credentials (username, password)

How to connect using python?
con = MySQLdb.connect(db='remoteDBname', host='192.***.***.***', user='remoteusername', passwd='yourpassword')
 
Did it connect?
It will throw an error indicating no access or incorrect credentials.

What next?
Of course you'd want to test out queries to use to get useful information, and this is where 'cursor' comes into play. This is important for executing single or multiple queries like in any other database command-line.

Creating a 'cursor' instance:
cursor = con.cursor(MySQLdb.cursors.DictCursor)

Executing a query:
get_all_query = "SELECT * FROM persons"
cursor.execute(get_all_query)

Fetching values returned after execution:
datarows_tuple = cursor.fetchall()

Then after acquiring all results from your query, you can process them according to your need(s).

Good Day :D