python - 如何根据条件在mysql中是否存在查询数据库?
问题描述
我想用不同的条件查询我的表,但这取决于客户端输入,例如:
SELECT * FROM t_user WHERE f_username like 'frank' and f_country = "%UK%".
由于我用 Python 编写了我的服务器,所以我的查询将是:
sql = """SELECT * FROM t_user WHERE f_username like '%s' and f_country = "%%s%"."""
cur.execute(sql, ('frank', 'UK'))
但是,有时,用户不想按国家/地区过滤,所以他们可能只会得到keyword
. 所以我的查询应该是这样的:
SELECT * FROM t_user WHERE f_username like 'frank'
另外,我的 python 会像:
sql = """SELECT * FROM t_user WHERE f_username like '%s'"""
cur.execute(sql, ('frank',))
然后,我可以检查参数,决定sql
我应该使用哪个,但是在我的实际项目中,它有很多过滤器要求,这可能会让我构建很多条件检查,比如:
if not country_id and not city_id and not keyword:
condition = """
WHERE f_username=%s
"""
elif country_id and not city_id and not keyword:
condition = """
WHERE f_username=%s and f_country=%s
"""
elif not country_id and city_id and not keyword:
condition = """
WHERE f_username=%s and f_city=%s
"""
elif not country_id and not city_id and keyword:
condition = """
WHERE f_username=%s and f_activity_title like (%%s%)
"""
elif country_id and city_id and not keyword:
condition = """
WHERE f_username=%s and f_country=%s and f_city=%s
无论如何,它有效。但我希望它更 Pythonic,比如:
WHERE f_username=(%s or '*') and f_country=(%s or '*' and f_city=(%s or '*)
我知道它不是真正正确的 sql 语法,但你能帮我找到一个好的吗?
解决方案
使用存储过程。
下面是一个 MySQL 过程示例:
(更新):
CREATE PROCEDURE country_hos
(IN country CHAR(50))
(IN Info CHAR(50))
begin
select * from t where
(country=@country OR @country is null) and
(info like '%'+@info+'%') -- if info is not provided and @info is empty then an empty string will return all the data.
End
SQL Server 过程示例:
create proc sp_someCatchyName
@country varchar(50),
@Info varchar(50)
as
begin
select * from t where
(country=@country OR @country is null) and
(info like '%'+@info+'%') -- if info is not provided and @info is empty then an empty string will return all the data.
end
但是,如果您打算按照 SQL 聊天室中的对话在 python 中执行内联 SQL,那么在搜索了一些关于 python 代码(虽然我不知道 python)之后,下面的代码应该会为您提供工作方向,您可以通过它实现你的目标:
内联python sql代码示例:
sql = """SELECT * FROM t_user WHERE f_username like '%s' and (f_country = "%%s%" OR %s is null)."""
cur.execute(sql, ('frank', 'UK')) //when both params given
cur.execute(sql, ('frank', null)) //when country is not given
推荐阅读
- java - 泛型参数的类文字
- azure - 从 aks 节点/pod 读取/写入文件到本地主机
- java - 尝试自动更新程序时出错
- sql - 左连接大表的 Teradata 性能问题
- vaadin - 如何禁用 vaadin 14 的未排序状态
- twilio - 如何跟踪来自 Twilio SMS 的链接点击
- javascript - 如何使网格方块改变颜色?
- android - Android Management API - 访问设备设置问题
- python-2.7 - 为什么 PyAudio Stream Callback 在 Pepper Robot 中不起作用?
- oracle-agile-plm - 关于在变更单操作菜单项中打开 URL