I would like to know how to use the count function when using sqlite in python to look up and return the number of specific values there are in a table. For example, I want to be able to look in an sqlite table showing students and their characteristics and be able to find how many of them are male or female using python. I have done some research but have only found relevant information for when you are just using sqlite.
Asked
Active
Viewed 1.1k times
1
-
Can you add the code that you've tried ? – Vikas Periyadath Jan 19 '18 at 09:00
-
What is your table schema? As it is now this is rather broad. Please consider trying out some tutorials like [this one](https://www.pythoncentral.io/introduction-to-sqlite-in-python/) or [this other one](https://www.blog.pythonlibrary.org/2012/07/18/python-a-simple-step-by-step-sqlite-tutorial/) first, and then either [this answer](https://stackoverflow.com/questions/17119151/count-male-female-and-total) or [this answer](https://stackoverflow.com/questions/43110609/count-number-of-male-and-female) may become useful (note how they are different/schema dependant). – metatoaster Jan 19 '18 at 09:01
1 Answers
10
Did you try this :
rowsQuery = "SELECT Count() FROM %s" % table
cursor.execute(rowsQuery)
numberOfRows = cursor.fetchone()[0]
you have to change the rowsQuery according to your need .
For your question:
rowsQuery = "select count(STUDENT) from table_name where Gender= 'Male'"

Adam Azam
- 93
- 1
- 1
- 7

Vikas Periyadath
- 3,088
- 1
- 21
- 33
-
This is just retrieving data from a table. I want to count the occurrence of a value in a table. – Adam Azam Jan 19 '18 at 09:06
-
count of a value that is in a particular column in that table ? – Vikas Periyadath Jan 19 '18 at 09:10
-
So you only need to change the query : `select count(primary_key_column) from table_name where Gender= "Male"` – Vikas Periyadath Jan 19 '18 at 09:15
-
1Please use SQL placeholders instead of building the query with string operations. See https://docs.python.org/3/library/sqlite3.html#sqlite3-placeholders – Cédric Van Rompay Jun 28 '21 at 09:57