When I'm using python to fetch results from a SQL database I get extra charters at the beginning and end of the returned value. For example the below code returns ((56L,),) instead of 56, does anyone know how to get just the value... and what the (( ,),) actually mean...?
hp= 56
id= 3
database = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "db")
cursor = database.cursor()
cursor.execute("UPDATE period_option SET points =%s WHERE period_option_id =%s", (hp, id))
cursor.execute("SELECT points FROM period_option WHERE period_option_id =%s", (po_id_home))
results = cursor.fetchall()
print results
fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. cursor.
fetchall() is list of tuples, but doc shows tuple of tuples. Bookmark this question.
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and is built on top of the MySQL C API. Packages to Install mysql-connector-python mysql-python.
rows = cursor.fetchall() The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.
2. Fetchall (): Fetchall () is a method that fetches all the remaining tuples from the last executed statement from a table (returns a list of tuples). The method only returns the first row from the defined table and If there are no tuples then it returns an empty list in the output.
When called repeatedly, this method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list. cursor.fetchone () method returns a single record or None if no more rows are available. I have created a database_developers table in my database.
cursor.fetchmany (size) returns the number of rows specified by size argument. When called repeatedly, this method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list.
fetchall()
returns a list (really: a tuple) of tuples. Think of it as a sequence of rows, where each row is a sequence of items in the columns. If you are sure your search will return only 1 row, use fetchone(), which returns a tuple, which is simpler to unpack. Below are examples of extracting what you want from fetchall() and fetchone():
# Use fetchall():
((points,),) = cursor.fetchall() # points = 56L
# Or, if you use fetchone():
(points,) = cursor.fetchone() # points = 56L
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With