0

I am trying to create a class and methods to connect to Mysql database and update a table according to the requirements that I have received. My code updates the table without using any class and methods but stops working as soon as I include the class.

Example Code -

import MySQLdb
from opswareConnect import data
from echoResourceConfig import host, user, passwd, db

class echoResource(object):
def __init__(self):
    self.host = host
    self.user = user
    self.passwd = pwsswd
    self.db = db
    self.cursor = self.connect()

def connect(self):
    try:
        self.cnx = MySQLdb.connect(host, user, passwd, db)
        if cnx:
           print(self.cnx)
        self.cursor = self.cnx.cursor()
    except Exception, e:
        print "Error"
    return self.cursor

def updateResource(self, cursor):
    select_query = "SELECT resource_id, resource_name, support_contact_id FROM echo_resource WHERE resource_name = (%s);"
    update_query = "UPDATE echo_resource \
                       SET support_contact_id = ( \
                           SELECT contact_id FROM contacts WHERE last_name = (%s)) \
                     WHERE resource_name = (%s);"

    for row in data:
        arg1 = [row["system_name"],]
        arg2 = [row["fdc_inv_sa_team"]]
        row = self.cursor.execute(select_query, arg1)
        if row:
               data = self.cursor.fetchall()
               for res in data:
                    print(res)

               upd_row = self.cursor.execute(update_query, (arg2, arg1))
               if not upd_row:
                    print("Update failed")
               else:
                    self.cnx.commit()
                    print("update successful")
        else:
             print("No data found for "+row["system_name"])
6
  • How are you instantiating and using this class? Commented Jun 26, 2017 at 18:22
  • I am simply running it using "python filename" command. @DanielRoseman Commented Jun 26, 2017 at 18:24
  • 2
    Well how are you expecting that to work? You've created a class, presumably so you can use it within other code. You need to actually call that class somewhere. Commented Jun 26, 2017 at 18:27
  • created an object and calling the methods. The connection is successful but the code is throwing an exception while running updateResource(). @DanielRoseman Commented Jun 28, 2017 at 16:59
  • Stop posting duplicate answers, and edit your question with the updated code. Commented Jun 28, 2017 at 17:06

3 Answers 3

1

Updated Code -

import MySQLdb
import logging
from opswareConnect import data
from echoResourceConfig import host, user, passwd, db, select_query, 
update_query, insert_query

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class echoResource(object):
def __init__(self):
    self.host = host
    self.user = user
    self.passwd = passwd
    self.db = db
    self.select_query = select_query
    self.update_query = update_query
    self.insert_query = insert_query


def connect(self):
    print "inside connect"
    try:
        self.cnx = MySQLdb.connect(host, user, passwd, db)
        if self.cnx:
            print("connection successful" , self.cnx)
        self.cursor = self.cnx.cursor()
    except Exception, e:
        print "Error"
    return self.cursor

def updateResource(self):
    try:
        for row in data:
            arg1 = [row["system_name"],]
            arg2 = [row["fdc_inv_sa_team"]]
        row = self.cursor.execute(self.select_query, arg1)
        print row
        if row:
        if row:
            data = self.cursor.fetchall()
            upd_row = self.cursor.execute(self.update_query, (arg2, str(datetime.now()), arg1))

            if not upd_row:
                print "upd_row", upd_row
                self.cursor.execute(self.insert_query, (arg1, arg2, "Update Failed", str(datetime.now())))
                self.cnx.commit()
            else:
                print "else"
                print upd_row
                self.cursor.execute(self.insert_query, (arg1, arg2, "Update Successful", str(datetime.now())))
                self.cnx.commit()
        else:
            self.cursor.execute(self.insert_query, (arg1, arg2, "Resource Not Present In Echo_Resource Table", \
                                        str(datetime.now())))
            self.cnx.commit()
    except Exception, e:
        print("Error")

def main():
echo_resource_obj = echoResource()
echo_resource_obj.connect()
echo_resource_obj.updateResource()

if __name__ == '__main__':
main()
Sign up to request clarification or add additional context in comments.

Comments

0

Question: Class does not print any statement while connecting

You are missing the self. prefix.
change

self.cnx = MySQLdb.connect(host, user, passwd, db)
    if cnx:

to

self.cnx = MySQLdb.connect(host, user, passwd, db)
    if self.cnx:

Comments

0

Updated the code and created an object to call the methods.

import MySQLdb
import logging
from opswareConnect import data
from echoResourceConfig import host, user, passwd, db, select_query, 
update_query, insert_query

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class echoResource(object):
def __init__(self):
    self.host = host
    self.user = user
    self.passwd = passwd
    self.db = db
    self.select_query = select_query
    self.update_query = update_query
    self.insert_query = insert_query


def connect(self):
    print "inside connect"
    try:
        self.cnx = MySQLdb.connect(host, user, passwd, db)
        if self.cnx:
            print("connection successful" , self.cnx)
        self.cursor = self.cnx.cursor()
    except Exception, e:
        print "Error"
    return self.cursor

def updateResource(self):
    try:
        for row in data:
            arg1 = [row["system_name"],]
            arg2 = [row["fdc_inv_sa_team"]]
        row = cursor.execute(select_query, arg1)
        print row
        if row:
            data = cursor.fetchall()
            upd_row = cursor.execute(update_query, (arg2, str(datetime.now()), arg1))

            if not upd_row:
                print "upd_row", upd_row
                cursor.execute(insert_query, (arg1, arg2, "Update Failed", str(datetime.now())))
                cnx.commit()
            else:
                print "else"
                print upd_row
                cursor.execute(insert_query, (arg1, arg2, "Update Successful", str(datetime.now())))
                cnx.commit()
        else:
            cursor.execute(insert_query, (arg1, arg2, "Resource Not Present In Echo_Resource Table", \
                                        str(datetime.now())))
            cnx.commit()
    except Exception, e:
        print("Error")

def main():
echo_resource_obj = echoResource()
echo_resource_obj.connect() 
echo_resource_obj.updateResource()

if __name__ == '__main__':
main()

Connection is successful but the code is throwing an exception and not executing the queries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.