【发布时间】: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