Newbie Question: Obtain element from list of tuples
Roy Smith
roy at panix.com
Sun Dec 18 16:10:25 EST 2011
In article <mailman.3807.1324241477.27778.python-list at python.org>,
Chris Angelico <rosuav at gmail.com> wrote:
> If you're absolutely certain that you'll always get precisely one
> value from a query, this becomes rather more useful:
>
> mode = conn.query("SELECT mode FROM config WHERE id=5")[0][0]
Although, if you're going to do that, you might as well take advantage
of the fetchone() method that most Python database APIs have and
eliminate one of the indexes. Typical code would be something like:
cursor.execute("SELECT mode FROM config WHERE id=5")
mode = cursor.fetchone()[0]
If you're going to be doing any database work in Python, you should be
familiar with the Python Database API Specification,
http://www.python.org/dev/peps/pep-0249/. Most of the vendor-specific
database modules have interfaces which hold pretty close to the style
described there.
You might also want to explore SQL_Alchemy. I personally find it
difficult and painful to work with, but it does have the powerful
advantage that it abstracts away all the vendor-specific differences
between databases.
More information about the Python-list
mailing list