如何在 sqlite 中使用 % 和类似的值?
How to use the % and like values in sqlite?
我正在基于 url 中的搜索参数的 Flask 中执行一条路线,将过滤数据库 return 所有相似的值,但我收到以下错误:接近“ %”:语法错误。
有人可以帮忙吗?
@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
您需要在字符串值周围加上单引号。使用参数更简单(也更有效):
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()
我正在基于 url 中的搜索参数的 Flask 中执行一条路线,将过滤数据库 return 所有相似的值,但我收到以下错误:接近“ %”:语法错误。 有人可以帮忙吗?
@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
您需要在字符串值周围加上单引号。使用参数更简单(也更有效):
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()