On 08/05/10 16:01, Νίκος wrote:
On 5 Αύγ, 22:09, Tim Chase<python.l...@tim.thechases.com> wrote:
dataset = cursor.fetchall()
for row in dataset:
print ( '''<tr> ''' )
So, 'dataset' in here is a 'list of tuples' right? and 'row'
in here is a tuple form the above list of tuples right?
Am i understanding this correctly?!
It was a tuple. But it migth as well be a list too?!?!
Could 'dataset' be a 'list of lists' as well?
Pretty much...it's either a list-of-tuples or a list-of-lists
(I'm not sure if is part of the DB-API spec to mandate one or the
other). For the most part, you can treat them as the same thing.
However, tuples are immutable, so you can't say
my_tuple[3] = some_value
but with a list you can:
my_list[3] = some_value
How one would know in which way the returned mysql data is saved in?
Well, you can ask:
print type(row)
(I *suspect* it's a tuple) or you can just tell it what to be:
for row in dataset:
row = list(row)
row[3] = row[3].strftime(...)
for item in row:
...
I don't usually have cause to write a value back into the data
I'm reading from the DB, so it's never really mattered to me
whether the DB gives me tuples or lists.
Though I think I'd make it a bit clearer by naming the fields:
for host, hits, dt in dataset:
print ("<tr>")
for item in (host, hits, dt.strftime(...)):
print ("<td>%s</td>" % item)
print ("</tr>")
Cool! I myself like this solution best over the all working other!
very nice approach thank you very much! Is what i anted and couldn't
write myself!
But please tell me if in my example 'row' was a tuple, what kind of
objects is 'host', 'hits', 'dt' here and how do they sore the data?
Python supports "tuple assignment" which means that the following
are about[*] the same:
# variant A
for row in dataset:
host = row[0]
hits = row[1]
dt = row[2]
# rest of your code here
# variant B
for row in dataset:
host, hits, dt = row
# rest of your code here
# variant C
for host, hits, dt in row:
# rest of your code here
The data-type of the individual values would be whatever comes
back from the database as translated into Python (string,
float/Decimal, boolean, datetime, etc). In your example, it's
likely a string+integer+datetime as the 3 values. You can see
why I prefer the elegance of just performing the assignment in
the for-loop (variant C).
Hope this helps,
-tkc
[*] "about" the same because in #1 and #2, you also have access
to the whole row; whereas in #3, you don't have something called
"row", but you could reassemble it if you needed:
row = (host, hits, dt)
--
http://mail.python.org/mailman/listinfo/python-list