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.
-
Can you add the code that you've tried ?Vikas Periyadath– Vikas Periyadath2018-01-19 09:00:42 +00:00Commented Jan 19, 2018 at 9:00
-
What is your table schema? As it is now this is rather broad. Please consider trying out some tutorials like this one or this other one first, and then either this answer or this answer may become useful (note how they are different/schema dependant).metatoaster– metatoaster2018-01-19 09:01:14 +00:00Commented Jan 19, 2018 at 9:01
Add a comment
|
1 Answer
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'"
4 Comments
Adam Azam
This is just retrieving data from a table. I want to count the occurrence of a value in a table.
Vikas Periyadath
count of a value that is in a particular column in that table ?
Vikas Periyadath
So you only need to change the query :
select count(primary_key_column) from table_name where Gender= "Male"Cédric Van Rompay
Please use SQL placeholders instead of building the query with string operations. See docs.python.org/3/library/sqlite3.html#sqlite3-placeholders