Python pandas pd.read_sql 带有下拉文本值中的参数

Python pandas pd.read_sql with parameter from dropdown text value

我正在使用:

我想执行SQL using pd.read_sql with parameter (dropdown1 default value is 'MTL')

   @app.callback(dash.dependencies.Output("graph1", "figure"),
          [dash.dependencies.Input("dropdown1","value")])

   def update_fig1(dropdown1_value):
          df = pd.read_sql('SELECT CONVERT(int,month) as month,CONVERT(int, revenue) as revenue FROM 
                            dbo.Sales_data where region = ' +   dropdown1_value +'',
          cnxn
          )

          df_month = df['month']
          df_revenue = df['revenue']
          data = [
                 {'x': df_month,
                  'y': df_revenue,
                  'type': 'line', 'name': 'SF'
                 }
                 ]

          return {'data': data}

我得到一个错误:

pandas.io.sql.DatabaseError:在 sql 'SELECT CONVERT(int,month) as month,CONVERT(int, revenue) as revenue FROM dbo.Sales_data where region = MTL' 上执行失败:('42S22',“[42S22] [Microsoft][SQL 服务器的 ODBC 驱动程序 17][ SQL 服务器] 无效的列名称 'MTL'。(207) (SQLExecDirectW)")

非常感谢任何可能的帮助!

如错误代码所示,您没有引用字符串 MTL 和 SQL 服务器默认将 MTL 理解为列引用。用单引号将您的值括起来,它应该可以工作。

      df = pd.read_sql('SELECT CONVERT(int,month) as month,CONVERT(int, revenue) as revenue FROM 
                        dbo.Sales_data where region = \'' +   dropdown1_value + '\'',

dropdown1_value为str值时,则使用:

sql = f'''
SELECT CONVERT(int,month) as month
    ,CONVERT(int, revenue) as revenue 
FROM dbo.Sales_data where region = '{dropdown1_value}'
'''
df = pd.read_sql(sql, cnxn)

dropdown1_value是一个列表值,那么使用:

sql = f'''
SELECT CONVERT(int,month) as month
    ,CONVERT(int, revenue) as revenue 
FROM dbo.Sales_data where region in {tuple(dropdown1_value)}
'''
df = pd.read_sql(sql, cnxn)