AttributeError: 'tuple' object has no attribute 'encode'

Paul Boddie paul at boddie.org.uk
Thu Apr 5 14:04:01 EDT 2007


erikcw wrote:
>
> Here is the full error: (sorry)

No problem! It's easier to comment with these details...

> Traceback (most recent call last):
>  File "/home/erik/Desktop/wa.py", line 178, in ?
> curHandler.walkData()
>  File "/home/erik/Desktop/wa.py", line 91, in walkData
> sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""",
> (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test'])
> AttributeError: 'long' object has no attribute 'encode'

If cid is a long, it won't have an encode method, but this is a
diversion from the real problem.

> sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""",
> (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test'])
> self.cursor.execute(sql)

This won't work because the first parameter of the execute method must
be a string (or Unicode object, I guess), but you've provided a tuple.

> Now, I changed all ofth e %i/%d to %s, and changed
> self.cursor.execute(sql) to self.cursor.execute(*sql) and it seems to
> be working now!

The first modification may not have been necessary, but you should
check the database module documentation to make sure what kinds of
parameter markers are permitted. The second modification should, as I
suspected, solve your problem. As you may be aware, adding the *
unpacks the contents of sql into the parameters for the execute
method. Thus, the first element in the tuple gets presented as the
first parameter (the SQL statement), and the second element gets
presented as the second parameter (a sequence of values which are to
be used with the SQL statement).

Paul




More information about the Python-list mailing list