【问题标题】:Retrieve data from SQL Server database using Python and PYODBC使用 Python 和 PYODBC 从 SQL Server 数据库中检索数据
【发布时间】:2021-07-01 20:19:36
【问题描述】:

我有 Python 代码,它使用 PYODBC 和 Streamlit 连接 SQL Server 数据库以创建 Web 应用程序。

问题是当我尝试使用多个条件执行选择查询时,结果为空,结果必须返回记录。

如果我直接在数据库上尝试 SQL 查询,它会返回以下结果:

SELECT        TOP (200) ID, first, last
FROM            t1
WHERE        (first LIKE '%tes%') AND (last LIKE '%tesn%')

作为来自 python 的查询,它返回 empty

sql="select * from testDB.dbo.t1 where ID = ? and first LIKE '%' + ? + '%' and last LIKE '%' + ? + '%' "
param0 = vals[0]
param1=f'{vals[1]}'
param2=f'{vals[2]}'
rows = cursor.execute(sql, param0,param1,param2).fetchall()

代码:

import pandas as pd
import streamlit as st

vals = []
expander_advanced_search = st.beta_expander('Advanced Search')
with expander_advanced_search:
for i, col in enumerate(df.columns):
      val = st_input_update("search for {}".format(col))
      expander_advanced_search.markdown(val, unsafe_allow_html=True)
      vals.append(val)
                                
      if st.form_submit_button("search"):
                            
         if len(vals)>0:
            sql='select * from testDB.dbo.t1 where ID = ? and first LIKE  ? and last LIKE ?  '
            param0 = vals[0]
            param1=f'%{vals[1]}%'
            param2=f'%{vals[2]}%'
            rows = cursor.execute(sql, param0,param1,param2).fetchall()
      df = pd.DataFrame.from_records(rows, columns = [column[0] for column in cursor.description])
      st.dataframe(df)
            

根据 Dale k 的建议,我在选择查询中使用 OR 运算符:

sql="select * from testDB.dbo.t1 where ID = ? OR first LIKE  ? or last LIKE ? "
param0 = vals[0]   # empty
param1=f'%{vals[1]}%' # nabi
param2=f'%{vals[2]}%' # empty 
rows = cursor.execute(sql, param0,param1,param2).fetchall()

显示结果:

all the records in the database

预期结果:

id first  last
 7 nabil jider

【问题讨论】:

  • 当你使用这样的参数时,这是正确的,值被引用。您需要执行以下操作 first LIKE '%' + ? + '%' 并从传入的参数值中删除 %
  • @DaleK 关于我发布图片的第一条评论是为了让我的问题更容易理解和更清楚。关于第二条评论,参数值将变为param1=f'{vals[1]}' ?
  • @DaleK 我试过你的第二条评论它仍然返回空结果。

标签: python sql-server pandas select pyodbc


【解决方案1】:

我认为这可能在您的参数中 - 您的表单仅提交第一个/最后一个值,但您的查询显示 ID=? 您没有提供表单中的 ID,因此没有结果。或者它将“first”输入中的值放入 vals[0] 中,结果查询正在寻找 ID = 'tes'。

另外,查看pd.read_sql() 将查询结果直接通过管道传输到 DataFrame/

如果您希望单独处理每个子句,您可能需要使用 OR 语句:

where ID = ? or first LIKE  ? or last LIKE ?'

【讨论】:

  • 我正在尝试使查询动态化,用户将在其中输入所需的输入之一或将所有这些输入... 关于Or it's putting the value from the 'first' input into vals[0] and the resulting query is looking for an ID = 'tes'. 我的答案是否定的,因为在调试中表明vals[0] is the ID vals[1] is the first vals[2] is the last
  • @khaledM_dev "ONE OF THE REQUIRED INPUT" 意味着您需要 OR 而不是 AND。 AND 表示需要 *ALL 输入。所以实际上您在代码中使用的查询与您在 SSMS 中运行的查询不同。
  • 这是一个更复杂的 where 子句来解释可能存在或不存在的三个值的组合。当您在表单上将 ID 留空时,您的调试器会在 vals[0] 中显示什么?
  • @DaleK 那么如何编写查询以允许用户输入 1 或 2 个字段,或者如果用户输入所有字段将缩小他的搜索范围。
  • @khaledM_dev 我猜是你,说你的查询在 SSMS 中有效,但在代码中无效。因此,我们假设您知道如何编写逻辑,只是不知道如何转换为从代码中调用。但是,您的真正问题似乎是您不了解如何编写逻辑。我在上面发布了几个 cmets 的链接解释了这一点。
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2019-01-20
  • 2012-07-12
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多