为什么pandas不执行sql查询?

问题描述 投票:1回答:1

为什么pandas不执行sql查询?

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()

查询产生的结果我想在SQL浏览器的SQL浏览器中使用

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

我的输出应该有11行

python sqlite pandas
1个回答
4
投票

引用有问题 - 试试这个:

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

您还可以使用以下技术:

qry = """
SELECT department, count(*) as cnt
FROM MyTable
WHERE CompletedTraining = 'Incomplete'
GROUP BY department
"""
df = pd.read_sql_query(qry, con)
© www.soinside.com 2019 - 2024. All rights reserved.