I would like to write a class that would contain all my MySQL operations.
Right now, I cant even get the class instantiated.
Traceback (most recent call last):
File "./compare.py", line 71, in <module>
main()
File "./compare.py", line 67, in main
db = Table.mysqlconnect()
TypeError: unbound method mysqlconnect() must be called with Table instance as first argument (got nothing instead)
code:
import MySQLdb
class Table(object):
""" Using Databases """
def __init__(self, db, name ):
self.db = db
self.name = name
self.cur = self.db.cursor()
def mysqlconnect():
conn = MySQLdb.connect (host = "mysql.blah.com",
user = "user",
passwd = "password",
db = "database")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
def main():
db = Table.mysqlconnect()
pass
if __name__ == '__main__':
main()
You should read those docs, but what you’re looking for is:
Short explanation:
mysqlconnectis a instance method on yourTableclass.Long explanation:
Tableis an abstract concept right now — you’ve told the Python interpreter about it and what it should do, but you haven’t actually made one yet. It’s like the blueprint, if you will, for your class. Before you use it, or use any method defined as part of it* you’ll need to actually “build it” first.This is what you do when you do:
db = Table()This tells the Python interpreter that I’ve got this variable calleddbnow and I want it to be an instance ofTable(). Now that you’ve got your instance, you can call the instance method (since the instance method only works on an instance) and get your result.*There are things called class methods that you can use without instantiating the class first, but you’ll see that when you read the documentation.