1

why doesn't pandas execute sql query?

import sqlite3
import pandas as pd

# load data
df = pd.read_csv('CurriculumAuditReport.csv')

# strip whitespace from headers
df.columns = df.columns.str.strip()

con = sqlite3.connect("sans.db")

# drop data into database
df.to_sql("MyTable", con, if_exists='replace')

df = pd.read_sql_query('SELECT Count (Department) FROM MyTable WHERE `CompletedTraining` LIKE 'Incomplete' GROUP BY Department', con)
print(df)


con.close()

the query produces the result i want just fine in DB browser for SQLite

the output 
    C:\sans>C:\python34\python test2.py
  File "test2.py", line 15
    df = pd.read_sql_query('SELECT Count (Department) FROM MyTable WHERE 
`CompletedTraining` LIKE 'Incomplete' GROUP BY Department', con)


                                   ^
SyntaxError: invalid syntax

my output should have 11 rows

5
  • The first thing to mention is that there is no point using LIKE without a wildcard, just use equals. Or add a wildcard(s) as appropriate. Commented Dec 28, 2017 at 20:42
  • what are you trying to count? Commented Dec 28, 2017 at 20:44
  • try using \'Incomplete\' instead in your code, hope that'll work. Commented Dec 28, 2017 at 20:44
  • so what should i use? Commented Dec 28, 2017 at 20:44
  • \'Incomplete\' may have done the trick, still need more editing! Commented Dec 28, 2017 at 20:44

1 Answer 1

4

You have an issue with quoting - try this:

df = pd.read_sql_query("SELECT Department, count(*) as cnt FROM MyTable WHERE CompletedTraining = 'Incomplete' GROUP BY Department", con)

You can also use the following technique:

qry = """
SELECT department, count(*) as cnt
FROM MyTable
WHERE CompletedTraining = 'Incomplete'
GROUP BY department
"""
df = pd.read_sql_query(qry, con)
Sign up to request clarification or add additional context in comments.

11 Comments

thank you, i was able to get it working, but using \'Incomplete\'
@davidjbeiler, this is a little bit unusual way of counting in SQL... What do you want to count?
counting all the 'incomplete' rows in my table/csv but i need to count per department and group by department
that gives me the total count, not count per department
@davidjbeiler, yeah, now it should show you all the departments (where CompletedTraining = 'Incomplete') together with the corresponding number of rows...
|

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.