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/