【问题标题】:Python: Class does not print any statement while connecting to MYSQL DatabasePython:连接到 MYSQL 数据库时,类不打印任何语句
【发布时间】:2017-06-26 18:17:11
【问题描述】:

我正在尝试创建一个类和方法来连接到 Mysql 数据库并根据我收到的要求更新表。我的代码在不使用任何类和方法的情况下更新了表格,但在包含该类后立即停止工作。

示例代码 -

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"])

【问题讨论】:

  • 你是如何实例化和使用这个类的?
  • 我只是使用“python 文件名”命令运行它。 @丹尼尔罗斯曼
  • 那么您希望它如何工作?您已经创建了一个类,大概是这样您就可以在其他代码中使用它。您需要在某个地方实际调用该类。
  • 创建了一个对象并调用了方法。连接成功,但代码在运行 updateResource() 时抛出异常。 @丹尼尔罗斯曼
  • 停止发布重复的答案,并使用更新的代码编辑您的问题。

标签: python function class methods mysql-python


【解决方案1】:

更新代码 -

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()

【讨论】:

    【解决方案2】:

    问题:类在连接时不打印任何语句

    您缺少self. 前缀。
    改变

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

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

    【讨论】:

      【解决方案3】:

      更新了代码并创建了一个对象来调用方法。

      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()
      

      连接成功,但代码抛出异常并且不执行查询。

      【讨论】:

        猜你喜欢
        • 2020-12-14
        • 2012-08-06
        • 2021-09-01
        • 2018-07-06
        • 2015-05-08
        • 2019-09-22
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多