python - flask mysql 不为空

标签 python mysql flask null

c.execute('SELECT * FROM image where year=%s and day=%s and month=%s and       
station=%s ',(year,day,month,station))

我使用此查询获取所有数据,并从代码下方的 html 页面获取数据

year = request.form.get('Year')
day = request.form.get('day')
month = request.form.get('Month')
station = request.form.get('Station')

但问题是如果我不写年的值,例如 年:空白日:22 月:5 站:牛津 它会导致错误,因为年份是空白的。所以我尝试使用 if 语句

if not station:
    if not year:
        if not month:
            if not day:
                  c.execute('SELECT * FROM image')

但我发现我必须制作 16 个 if,else 语句,所以我尝试了其他方法。当我不写站值并自己使其不为空时 并尝试将其用于我上面编写的原始代码。

c.execute('SLECT * FROM image where year %s and day =%s and month = %s and station=%s',(year,day,month,station))

但我没有按预期工作。我想使用那个查询,如果 null 进入那个查询我想显示来自数据库的所有数据值。 如果您能提供帮助,我将不胜感激。

这是我更新的。

def construct_condition(field_name, field_value):
    return field_name + " = " + str(field_value) if field_value else      field_name + " like '*'"

@app.roue("/day/",methods =['GET','POST'])
def day():
    station = request.form.get('Station')
    year = request.form.get('Year')
    month = request.form.get('Month')
    day = request.form.get('Day')
    c,conn = connection()

    sql = "select * from table where ' + ' and ".join([
    construct_condition("year", year), 
    construct_condition("day", day), 
    construct_condition("month", month), 
    construct_condition("station", station)])

c.execute(sql)
datas=c.fetchall()
conn.close()

最佳答案

你可以定义一个函数来根据字段的值构造过滤条件,如下所示:

def construct_condition(field_name, field_value):
    return field_name + " = " + str(field_value) if field_value else  field_name + " like '*'"

sql = "select * from table where " + " and ".join([
    construct_condition("year", year), 
    construct_condition("day", day), 
    construct_condition("month", month), 
    construct_condition("station", station)])

c.execute(sql)

关于python - flask mysql 不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49972448/

相关文章:

python - 有人可以帮我查明 Bcrypt 失败的原因(ValueError : Password must be non-empty)

python - FLASK Restful API 无法使用 PUT 添加

python - python 如何检查一个列表是否在另一个具有相同顺序的列表中

php - 即使我的数据库没有使用 angular.js 和 PHP 的值,在表中获取多行

Flask Admin 一对一关系和编辑表单

python - 如何将 Huey 连接到 Flask 应用程序

python - 将列表更改为字符串

python - 向 Python 脚本发送消息

php - mysql删除datetime与系统时间最接近的数据

mysql - 在 MySQL 中按计数输出分组?