简体   繁体   中英

Mysqldb update error typeerror 'str' object is not callable

I have created a database with MySQLdb. In database I have a table with name student with columns:

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

I update a row with a function Update. My code is below:

    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()

When I run the function i take the follow error:

typeerror 'str' object is not callable

I use f and l to be callable but nothing.
I need some help here to solve that problem. Thanks!

There may be other problems, but let's start with this:

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

...is wrong.

You need a comma between the arguments:

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

Your code looks like a function call: this_is_how_we_call_a_func() <- note the parens!
But sql2 only contains a string, which is -- as the evidence will show -- not callable...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM