如何在熊猫中执行多个查询?

时间:2019-12-16 10:45:31

标签: python sqlalchemy

如何使用sqlalchemy执行以下查询?

import pandas as pd
import urllib
from sqlalchemy import create_engine
from sqlalchemy.types import NVARCHAR
params = urllib.parse.quote_plus(r'DRIVER={SQL Server};SERVER=localhost\SQLEXPRESS;Trusted_Connection=yes;DATABASE=my_db;autocommit=true;MultipleActiveResultSets=True')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str, encoding = 'utf-8-sig')

with engine.connect() as con:
    con.execute('Declare @latest_date nvarchar(8);')
    con.execute('SELECT @latest_date = max(date) FROM my_table')
    df = pd.read_sql_query('SELECT * from my_db where date = @latest_date', conn_str)

但是,发生了错误:

sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the scalar variable "@latest_date". (137) (SQLExecDirectW)')

如何解决这个问题?

谢谢。

1 个答案:

答案 0 :(得分:0)

您无需声明变量并使用大量查询,只需执行一个查询即可:

SELECT * 
FROM my_db 
WHERE date = (SELECT max(date) 
              FROM my_db)

然后您可以使用,我使用反引号,因为日期是保留字:

with engine.connect() as con:
    query="SELECT * FROM my_db WHERE `date` = (SELECT max(`date`) FROM my_db)"
    df = pd.read_sql(query, con=con)