Python Forum
Reading in MYSQL data as integer type
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading in MYSQL data as integer type
#1
Hi,
I'm using mysql.connector to query my databases but I'm having trouble with the data type returned.
in my query result I'm just looking for a count of all the rows in a table and I'm using the query:

 
getCount.execute("SELECT count(*) from tablename")
countresult = getCount.fetchall()
This does return the value I want i.e. 10, however the returned data is [(10,)] which I then have to string format and convert into an
integer.
I can't seem to figure out the quick way to return the value just as an integer to shorten my code.
Any tips would be greatly appreciated.

Thanks
Dave
Reply
#2
fetchall() will return list of tuples (or list of some other data container like dict, depending on options).
your query will return a single value and that value is of type int
so countresult will be list of tuple with one element

so to get the value as int:
my_count = countresult[0][0]
now, how can you improve it?
Use fetchone() in this case. it will return just one row - a tuple with one value of type int
then
countresult = getCount.fetchone()
my_value = countresult[0]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Oh great, thanks very much! That makes sense :-)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Mysql and mysql.connector error lostintime 2 612 Oct-03-2023, 10:25 PM
Last Post: lostintime
  reading a table which is of type string saisankalpj 2 927 Dec-03-2022, 11:19 AM
Last Post: saisankalpj
  Reading All The RAW Data Inside a PDF NBAComputerMan 4 1,276 Nov-30-2022, 10:54 PM
Last Post: Larz60+
  Reading Data from JSON tpolim008 2 1,032 Sep-27-2022, 06:34 PM
Last Post: Larz60+
  Mysql error message: Lost connection to MySQL server during query tomtom 6 15,685 Feb-09-2022, 09:55 AM
Last Post: ibreeden
  Help reading data from serial RS485 korenron 8 13,604 Nov-14-2021, 06:49 AM
Last Post: korenron
  Help with WebSocket reading data from anoter function korenron 0 1,300 Sep-19-2021, 11:08 AM
Last Post: korenron
  Fastest Way of Writing/Reading Data JamesA 1 2,139 Jul-27-2021, 03:52 PM
Last Post: Larz60+
  SaltStack: MySQL returner save less data into Database table columns xtc14 2 2,115 Jul-02-2021, 02:19 PM
Last Post: xtc14
  Reading data to python: turn into list or dataframe hhchenfx 2 5,280 Jun-01-2021, 10:28 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020