Reputation: 3
I'm trying to use the results of a mysql query as the values for a variable in a loop. However, the results from the query are returned as a tuple with the value indicating a long integer. Here's the example result: ((2136L,),(41L,),(340L,),...etc)
For some reason, when I try to use the results, the value literally contains the "L," suffix, and so I can't use it at all. Because it is a tuple, I can't change it to an integer and drop the suffix.
Here's the basic version of my code:
db = MySQLdb.connect("localhost","root","password","testdb")
cursor = db.cursor()
sql = ("SELECT thisid FROM thislist")
cursor.execute(sql)
data = cursor.fetchall()
mynumber = str(data[0]) #here i get (2136L,) instead of '2136'
mystring = 'The last thing should be a number as a string: ' + mynumber
The end result is "The last thing should be a number as a string: 2136L,", when what I need is "...as a string: 2136".
I'm a python noob, but I've just been having the hardest time finding a solution to what I imagine is a pretty simple problem. Thanks!
Upvotes: 0
Views: 79
Reputation: 599590
fetchall()
returns a tuple of tuples; in other words, it returns a tuple of rows, each of which is itself a tuple of columns. That means that data[0]
in your code is still a tuple.
You could fix this by accessing data[0][0]
, but in your case, since you only want to fetch one row, you could use fetchone()
and still access data[0]
.
Upvotes: 2