简体   繁体   中英

Python: Flask request.args.get that contain null value in tables

I have table in MySQL that I need to get from app. It works perfectly fine if the data does not contain 'null' value, but if the data contains null value, I unable to search it.

@app.route('/ABC/search1', methods=['GET'])
def ABCsearch1():
    name = request.args.get('name',default='',type=str)
    priceMin = request.args.get('priceMin',default='',type=str)
    priceMax = request.args.get('priceMax',default='',type=str)

        limit = request.args.get('limit',default=0,type=int)
    offSet = request.args.get('offSet',default=0,type=int)

    query = """ SELECT * FROM KLSE WHERE (Stock LIKE :s0 or Name LIKE :s1 or Number LIKE :s2)
                AND (Price BETWEEN (IF(:s3='_',-5000,:s4)) AND (IF(:s5='_',5000,:s6)))
                LIMIT :s95 OFFSET :s96 """
    query = text(query)
    input = {'s0':name+"%",'s1':name+"%",'s2':name+"%",'s3':priceMin,'s4':priceMin,'s5':priceMax,'s6':priceMax,
                's95':limit,'s96':offSet}
    try:
        call = db.session.execute(query,input)
        f = call.fetchall()
        col = ['index','Stock','Name','Number','Price','id']
        f1 = [OrderedDict(zip(col,t)) for t in f]
    except Exception:
        return 'Error'

    return jsonify({'Stock': f1})

Example, if Stock 'XYZ' has price 3,'XYZZ' is price at 3.4 and 'XYZA' is price null in database. When I serach for 'XY' in name, it will only shows 'XYZ' and 'XYZZ'. 'XYZA' will not appear as it null.

I need whatever is match with 'XY', even the price is null, I want it to be shown.

NULL is not a value it's the absence of a value thus you can't run comparisons on it. Add OR Price is NULL to your where clause. If you want to provide a default value you can add IFNULL(Price, '$0.00') to your selector string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM