Python:MySQL连接类包装器

时间:2014-09-25 14:28:09

标签: python mysql

我正在尝试在类中包装一个mysql连接示例,但是我做错了什么并在调用execute()时出错。

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

我的代码在这里:

#!/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提示符我执行以下操作:

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

但是得到这个错误:

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! (显然我是一个Python NOOB)

1 个答案:

答案 0 :(得分:1)

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

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