1

I am trying to wrap a mysql connection example in a class, but I have done something wrong and get an error when calling execute().

The mysql connection example is here: How do I connect to a MySQL Database in Python?

My code is here:

#!/usr/bin/python
import MySQLdb
import MySQLdb.cursors

class db ( object ) :
    # the database class"
    host   = "1.2.3.4"
    user   = "myuser"
    passwd = "mypass"
    dbname = "mydb"

    def __init__ ( self ) :
        self.conn = MySQLdb.Connection
        self.cur  = MySQLdb.cursors.Cursor

    def connect ( self ) :
        # connect to the database"
        self.conn = MySQLdb.connect ( host, user, passwd, dbname )
        self.cur = self.conn.cursor()

    def execute ( self, statement ) :
        # execute the given sql statement"
        self.cur.execute ( statement )

    def show ( self ) :
        # print the first cell of all the rows"
        for row in self.cur.fetchall() :
            print row[0]

So from the ipython prompt I do the following:

from myfile import *
x=db()
x.connect
x.execute("select * from mytable")

But get this error:

myfile.py in execute(self, statement)
     19         self.__cur__ = self.__conn__.cursor()
     20 
---> 21     def execute ( self, statement ) :
     22         # execute the given sql statement"
     23         self.cur.execute ( statement )

TypeError: unbound method execute() must be called with Cursor instance as first argument (got str instance instead)

HELP! (obviously I am a Python NOOB)

Community
  • 1
  • 1

1 Answers1

2

Don't forget to call the x.connect method:

x = db ()
x.connect() # not x.connect
x.execute(...)
David542
  • 104,438
  • 178
  • 489
  • 842