2

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.

2
  • Can you add the code that you've tried ? Commented 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). Commented Jan 19, 2018 at 9:01

1 Answer 1

12

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'"
Sign up to request clarification or add additional context in comments.

4 Comments

This is just retrieving data from a table. I want to count the occurrence of a value in a table.
count of a value that is in a particular column in that table ?
So you only need to change the query : select count(primary_key_column) from table_name where Gender= "Male"
Please use SQL placeholders instead of building the query with string operations. See docs.python.org/3/library/sqlite3.html#sqlite3-placeholders

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.