Python通过PYODBC连接SQL Server执行多条件查询结果异常问题
问题根因分析
- AND查询无结果:你直接在数据库执行的测试SQL没有ID筛选条件,但Python侧的查询强制添加了
ID = ?的约束,当ID参数为空或不匹配目标记录时,多个AND条件同时校验不通过,自然返回空结果。 - OR查询返回全表:你传入的ID参数、last参数均为空,此时查询条件变为
ID = '' OR first LIKE '%nabi%' OR last LIKE '%',其中last LIKE '%'会匹配所有非空的last字段,相当于全局无过滤,最终返回全表数据。
修复方案
核心逻辑是动态拼接查询条件,仅对用户有输入的字段添加筛选规则,避免空值参数干扰查询逻辑,同时保留参数化查询防SQL注入的特性。
修复后的业务代码参考:
import pandas as pd import streamlit as st # 初始化查询条件和参数列表 conditions = [] params = [] 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) # 仅当用户有输入时,添加对应筛选条件 if val.strip(): if col == 'ID': conditions.append("ID = ?") params.append(val.strip()) elif col == 'first': conditions.append("first LIKE ?") params.append(f"%{val.strip()}%") elif col == 'last': conditions.append("last LIKE ?") params.append(f"%{val.strip()}%") if st.form_submit_button("search"): # 拼接最终SQL if conditions: sql = "select * from testDB.dbo.t1 where " + " AND ".join(conditions) else: # 无任何输入时可返回全表或提示用户输入,按需调整 sql = "select * from testDB.dbo.t1" rows = cursor.execute(sql, params).fetchall() df = pd.DataFrame.from_records(rows, columns = [column[0] for column in cursor.description]) st.dataframe(df)
按照你的需求,当仅输入first字段值为nabi时,最终生成的SQL为select * from testDB.dbo.t1 where first LIKE ?,传入参数为['%nabi%'],即可正确返回ID为7的目标记录。
内容的提问来源于stack exchange,提问作者DevLeb2022
相关产品推荐
相关产品推荐

