Mysqldb更新错误类型错误' str'对象不可调用

时间:2012-03-17 18:28:11

标签: python mysql wxpython mysql-python wxwidgets

我用MySQLdb创建了一个数据库。 在数据库中,我有一个名为student的表,其中包含列:

id(is int),
id_user(is int),
f_name(is str),
l_name(is str)

我使用函数Update更新了一行。 我的代码如下:

    def UpdateUser(self,e):         
        self.checkid_user=int(self.updateid[0]) #ok there
        self.c2name=self.name.GetValue() #this is from a textctrl in wxpython
        self.c2lastname=self.lastname.GetValue()#this is from a textctrl in wxpython

        ne=self.c2name.encode("utf-8")#greek word
        fe=self.c2lastname.encode("utf-8")#greek word

        f="'"+str(ne)+"'"
        l="'"+str(fe)+"'"

        print f #ok
        print l #ok
        db=mdb.connect(host="localhost",use_unicode="True",charset="utf8",user="root",passwd="root",db="test")
        cursor = db.cursor()

        sql="""SELECT id_user FROM student"""

        try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
        except:
            # Rollback in case there is any error
            db.rollback()

        rows = cursor.fetchall()

        for row in rows:
            r=int(row[0])
            if r==self.checkid_user:                    #ok there
                sql2 = """UPDATE student
                SET f_name=%s,l_name=%s
                WHERE id_user=%s"""

               # Execute the SQL command
                cursor.execute(sql2(f,l,r))
        # Commit your changes in the database
                db.commit()

                db.rollback()
# disconnect from server
db.close()

当我运行该功能时,我采取了以下错误:

typeerror 'str' object is not callable

我使用fl可以调用但没有任何内容 我需要一些帮助来解决这个问题。谢谢!

1 个答案:

答案 0 :(得分:4)

可能还有其他问题,但让我们从这开始:

cursor.execute(sql2(f,l,r))

......错了。

参数之间需要逗号:

cursor.execute( sql2, (f,l,r) )

您的代码看起来像一个函数调用:this_is_how_we_call_a_func()< - 注意parens!
但是sql2只包含一个字符串,正如证据所示 - 不可调用......

>>> dir(sql2)
['__add__', '__class__', '__contains__', '__delattr__', ... other stuff

>>> def my_func(): pass
...
>>> dir(my_func)
['__call__', '__class__', '__closure__', '__code__', ... other stuff
 ^^^^^^^^^^
相关问题