[Tutor] for loops when there is only one row in the result - is there an alternative?
Rance Hall
ranceh at gmail.com
Fri Nov 26 03:28:28 CET 2010
Im using the py-postgresql module (docs here:
http://python.projects.postgresql.org/docs/1.0/)
in a python 3.1 environment to connect to my database.
so far everything is working, but I'm having trouble understanding the
structure of the variable returned by a select statement
Generally you have something like this:
clientlist = get_clients() # where get_clients is a prepared sql statement.
normally you would get the individual rows like this:
for row in clientlist:
do stuff
which is great for a long list of results. But I'm running into
issues when there are only 0 or 1 results in the set.
if there are zero rows then I can do something like:
if len(clientlist) == 0:
do stuff
I'm looking for a better way to access the row when there is just one
row in the result.
Say from a user login attempt, or a request to edit an existing client record.
Is there a decent way to get direct access to the single row in the
result set without having to go through the for loop for just one
item?
It likely helps to know exactly what variable type clientlist would
be. I have no idea.
What I can say is that once you do get the row result, you can refer
to values in the row with syntax like row["columnname"], but I'm
honestly not sure if this is helpful information.
Ive read the module docs looking for something interesting, but I
can't seem to find this particular tidbit.
If I have to do the for loop fine, but I just thought it looked a little ugly.
Rance
More information about the Tutor
mailing list