Monday, November 22, 2010

PyGame and GUI Programming - Multiple Database Access - Part II

This is the connect_server.py file. This module will be imported in the connection py file(previous post), this is just a common piece of coding, which connects to the database and returns a connection object, being a C# programmer i can see only the DATA as a DATATABLE rather than a recordset...:-)

so a method getDataTable will retun a record set for the query passed.

and ofcourse a main method to test the code(which is executed only during command line execution of this file and not during IMPORTS)

import MySQLdb

class databaseOps():
    '''
    This class is used to connect to the database, the connection object is accessed
    with the variable db
    '''
    def __init__(self,hosts,username,password,database):
    #open a connection if it does not have one already
        self.db = MySQLdb.connect(host=hosts, user=username , passwd=password, db=database)

    def get_data_table(self,query):
        cursor = self.db.cursor()
        try:
            cursor.execute(query)
            return cursor
        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit (1)

def main():
    f = databaseOps('localhost','root','1234','MyFirst')
    print 'Connection successful !!!'

if __name__ == '__main__':
    main()

No comments:

Post a Comment