【问题标题】:flask mysql not null烧瓶mysql不为空
【发布时间】:2018-10-02 23:44:53
【问题描述】:
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 进入那个查询我想显示来自 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()

【问题讨论】:

    标签: python mysql flask null


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 它说 pymysql.err.ProgrammingError: (1064, '您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以获取在 \'year 附近使用的正确语法\'*\'select * from image where "+" and day like \'*\'select * from image\' at line 1') 像这样...
    • 你能更新你用来生成sql的代码吗?
    • 我无法使用更新的代码重现错误。错误\'year like \'*\'select * from image where " + " and day like \'*\'select * from image\' 表示您多次连接select * from image。在执行之前尝试打印sql。
    • 天哪……先生,您还需要什么?在这里上传所有代码???非常感谢...
    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多