Python使用超类的mysql连接

时间:2014-12-06 08:55:27

标签: python mysql mysql-connector-python

以下是提供错误的示例代码,我希望能够获得有关修复的帮助,或者了解更好的编写方法。我有一个mysql" super"类叫mysql_connection。在此类中,建立与数据库的连接。我也有一些方法。只需运行"选择版本()"表明连接/查询有效。然后我有一个" chktable"在这个例子中实例化一个名为" table"的新子类的方法。它继承了超类。在实例化类之后,我然后在子类中调用一个方法,该方法尝试使用超类中的查询方法来运行"显示类似于' tbl name'"的表。这是我收到错误的地方。

import mysql.connector
from mysql.connector import errorcode
from mysql.connector.cursor import MySQLCursor

class mysql_connection(object):
    def __init__(self, **kwargs):
        self.connection_options = {}
        self.connection_options['user'] = 'root'
        self.connection_options['password'] = ''
        self.connection_options['host'] = '192.168.33.10'
        self.connection_options['port'] = '3306'
        self.connection_options['database'] = "test"
        self.connection_options['raise_on_warnings'] = True
        self.connect()

    def connect(self):
        try:
            self.cnx = mysql.connector.connect(**self.connection_options)
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print "Something is wrong with your user name or password"
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print "Database does not exists" 
            else:
                print err

    def query(self, statement, data=''):
        cursor = MySQLCursor(self.cnx)
        cursor.execute(statement)
        result = cursor.fetchall()
        cursor.close
        return result

    def get_version(self):
        print self.query("select version()")

    def chktable(self, tb_name):
        tab = table(name=tb_name)
        tab.check_table()

class table(mysql_connection):
    def __init__(self, **kwargs):
        self.name = kwargs['name']

    def check_table(self):
        return super(table, self).query("show tables like '{}".format(self.name))

conn = mysql_connection()
conn.get_version()
conn.chktable("test")

我得到的错误是:

$ python example.py
[(u'5.1.73',)]
Traceback (most recent call last):
  File "example.py", line 50, in <module>
    conn.chktable("test")
  File "example.py", line 39, in chktable
    tab.check_table()
  File "example.py", line 46, in check_table
    return super(table, self).query("show tables like '{}".format(self.name))
  File "example.py", line 28, in query
    cursor = MySQLCursor(self.cnx)
    AttributeError: 'table' object has no attribute 'cnx'

我不完全理解回调超级类以及它如何与子类一起工作,所以这可能是我的问题。我也想知道是否有更好的方法来实现这一目标。我以为我可以完全摆脱子类,但我喜欢我制作的子类,所以我觉得应该有办法绕过它。我可以尝试的第二件事是将子类放在大师班中,但我不认为这是正确的。

1 个答案:

答案 0 :(得分:2)

Jon指出,这不是对继承的适当使用。那就是&#34; is-a&#34;关系:即狗继承自动物,因为狗是动物。但是表不是连接:表可能使用连接,但这只是意味着您应该将连接的实例分配给表中的实例变量。

此外,在继承关系中,超级类通常没有充分的理由知道它的子类,就像在chktable方法中一样。

(你看到的实际错误是因为你还没有在表__init__中调用超类方法,但是修复你的结构会更好。)