[Tutor] Declaring variables
Ben Finney
ben+python at benfinney.id.au
Thu Apr 7 18:33:38 EDT 2016
Dimitar Ivanov <dimitarxivanov at gmail.com> writes:
> I have a (hopefully) quick and easy to explain question. I'm currently
> using MySQLdb module to retrieve some information from a database. In
> my case, the result that's being yield back is a single line.
Just a note: The term is a “record” or “tuple”. It may be presented by
some tools as a line of text, but that's not what it represents.
> As far as my understanding goes, MySQLdb function called 'fetchone()'
> returns the result as a tuple.
That depends on how you asked for it.
The MySQLdb API provides a ‘DictCursor’ class that will return each
record as a Python ‘dict’, with field names as the keys.
> Problem is, the tuple has some unnecessary characters, such as an
> additional comma being returned. In my case:
>
> >>> idquery = 'select id from table;'
> >>> cur = mysql.cursor()
> >>> cur.execute(idquery)
> >>> id = cur.fetchone()
> >>> print id
> ('idinhere',)
Again, you are confused between the value and its textual
representation.
A tuple is a collection of values, not a string of text. But when
representing that to you, Python needs to show it as text. In this case,
it represents the value as you might type it in Python syntax. The text,
though, is not the value.
You are also confused about what is returned.
The row is always returned as a collection of fields. In that case, it
is a Python ‘tuple’ (but you can also arrange for it to be a Python
‘dict’, as mentioned above).
This is true whether the record contains one field, no fields, or
seventeen fields. It is always returned as a collection of fields.
So to get an individual field from that record, you need to extract the
desired item from the collection.
record = cur.fetchone()
id = record[0]
> Thanks a lot in advance! I hope I posted all the details needed and my
> question is easy to comprehend.
Your question was well written and you provided good information. I hope
this helps.
--
\ “Apologize, v. To lay the foundation for a future offense.” |
`\ —Ambrose Bierce, _The Devil's Dictionary_, 1906 |
_o__) |
Ben Finney
More information about the Tutor
mailing list