烧瓶mysql并非空


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,所以我尝试了其他方式。当我不编写电台价值而不是一个人零并试图将其用于我上面写的原始代码。

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

,但我不工作我的期望。我想使用该查询,如果null进入该查询,我想显示DB中的所有数据值。如果您有帮助,我真的很感激。

这是我更新的。

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)

相关内容

  • 没有找到相关文章

最新更新