Search code examples
pythonsqlsqlitewhere-clausesql-like

How to use the % and like values in sqlite?


I am doing a route in flask that based in the search param in the url is going to filter the database return all the similar values, but im getting the following error: near "%": syntax error. can anyone help?

@app.route('/courses/<search>', methods=['GET'])
    def searchg(search):
            con = sqlite3.connect('data.db')
            cur = con.cursor()
            courses = f'select id,name,description,tags,adminId,content,image from courses where name LIKE %{search}%'
            cur.execute(courses)
            allcourses=cur.fetchall()
            con.close()
            courseList = []
            for c in allcourses:
                formattedcourses = {"id":c[0],"name":c[1],"description":c[2],"tags":eval(c[3]),"adminId":c[4],"content":eval(c[5].replace("#",'"')),"image":c[6]}
                courseList.append(formattedcourses)
            return jsonify(courseList),200

Solution

  • You need single quotes around the string value. It is simpler (and more efficient) with parameters:

    cur = con.cursor()
    courses = f'select id,name,description,tags,adminId,content,image from courses where name LIKE ?'
    cur.execute(courses, ('%' + search + '%',))
    allcourses=cur.fetchall()