【问题标题】:How can I use multiple parameters using pandas pd.read_sql_query?如何使用 pandas pd.read_sql_query 使用多个参数?
【发布时间】:2017-03-04 00:21:56
【问题描述】:

我试图在 sql 查询中传递三个变量。这些是区域、功能、新用户。我正在使用 SQL 驱动程序 SQL Server Native Client 11.0。

这是我的有效代码。

query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS  WHERE Region = ?"

data_df = pd.read_sql_query((query),engine,params={region})

输出。

     LicenseNo
 0           12
 1            5

相反,我想传入三个变量,但这段代码不起作用。

query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS WHERE Region = ? and FeatureName = ? and NewUser =?"

nnu_data_df = pd.read_sql_query((query),engine,params={region, feature, newUser})

输出返回一个空数据框。

Empty DataFrame
Columns: [LicenseNo]
Index: []

【问题讨论】:

    标签: python sql-server pandas parameter-passing


    【解决方案1】:

    在元组中尝试一个字符串,也可以在查询中取出():

    所以你可以做类似的事情

    query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS WHERE Region = ? and FeatureName = ? and NewUser =?"
    region = 'US'
    feature = 'tall'
    newUser = 'john'
    data_df = pd.read_sql_query(query, engine, params=(region, feature , newUser))
    

    【讨论】:

    • 嗨 Steven - 我将 region、feature 和 newUser 转换为字符串并使用了您的语法,但仍然返回一个空数据框。
    • query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS WHERE Region = ? and FeatureName = ? and NewUser =?" Region = str(region) FeatureName = str(feature) NewUser = str(newUser) nnu_data_df = pd.read_sql_query(query,engine, params=(Region, FeatureName, NewUser))
    • 对不起,史蒂文我忘了给你加标签
    • 即使使用雪花 sql 也能工作吗?即使设置了snowflake.connector.paramstyle='qmark',它对我也不起作用。
    【解决方案2】:

    我的操作员错误:(我使用了错误的变量并且数据库没有返回任何结果,因为它不存在!

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 2018-04-08
      • 1970-01-01
      • 2014-12-08
      相关资源
      最近更新 更多