不为空

tyky79it  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(377)
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')

但问题是,如果我不写year的值,例如year:blank day:22 month:5 station:oxford,它会导致错误,因为year是空的。所以我试着用if语句

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

但我发现我必须做16个if,else语句,所以我尝试了其他方法。当我不写station值并将其设置为notnull时,我试图将其用于我上面编写的原始代码。

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

但我的工作没有达到我的预期。我想使用这个查询,如果null为get,我想显示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()
62lalag4

62lalag41#

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

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)

相关问题