如何使用pandas pd.read_sql_查询使用多个参数?

2024-06-06 04:39:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个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: []

Tags: 代码fromsqllicensewherequeryselectoptions
2条回答

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

所以你可以做些

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

运算符错误:(我使用了错误的变量,数据库没有返回任何结果,因为它不存在!

相关问题 更多 >