2014-09-25 90 views
0

我想在一个类中包装一个mysql连接的例子,但我做了一些错误,并在调用execute()时出错。Python:一个MySQL连接类包装

MySQL连接例子是在这里:How do I connect to a MySQL Database in Python?

我的代码是在这里:

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

但得到这个错误:

#!/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] 
从IPython中提示我做以下

所以:

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) 

帮助! (显然我是一个Python NOOB)

回答

1

不要忘记调用x.connect方法:

x = db() 
x.connect() # not x.connect 
x.execute(...)