栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用原始SQL查询实现搜索功能

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用原始SQL查询实现搜索功能

我为您创建了一个具有完整解决方案的github :)

https://github.com/researcher2/stackoverflow_57120430

有两件事:

避免SQL注入

我建议在执行原始sql语句时使用绑定,我的代码反映了这一点。我花了很长时间尝试使它与您的陈述相符,然后才绊倒于此:

在LIKE中使用通配符替换Python
SQLite参数

基本上,您不能将绑定放在LIKE’%?%’内,因为引号会导致替换令牌被忽略。

相反,您只需要执行LIKE?并手动建立替代品。

使用会议

所有会话信息都是JSON序列化的,然后发送到客户端。在这种情况下,行记录不是JSON可序列化的。这对我来说是一个错误:

TypeError: Object of type 'RowProxy' is not JSON serializable

我可能不会在这里使用该会话,因为客户端不需要知道这一点,因为无论如何您将用信息来构建一个漂亮的html页面。只需使用python字典并将其传递给模板引擎即可。我的代码确实使用了会话,因为这是您开始的过程。

万一github崩溃了:

from flask import request, render_template, sessionfrom app import app, db@app.route("/", methods=['GET','POST'])def index():    if request.method == "POST":        searchQuery = request.form.get("searchQuery")        print(searchQuery)        # Avoid SQL Injection Using Bindings        sql = "SELECt isbn, author, title     FROM book     WHERe isbn LIKE :x     OR author LIKE :y     OR title LIKE :z"        # I spent an hour wondering why I couldnt put the bindings inside the wildcard string...        # https://stackoverflow.com/questions/3105249/python-sqlite-parameter-substitution-with-wildcards-in-like        matchString = "%{}%".format(searchQuery)        stmt = db.text(sql).bindparams(x=matchString, y=matchString, z=matchString)        results = db.session.execute(stmt).fetchall()        print(results)        session["books"] = []        for row in results: # A row is not JSON serializable so we pull out the pieces book = dict() book["isbn"] = row[0] book["author"] = row[1] book["title"] = row[2] session["books"].append(book)        return render_template("index.html", searchedFor=searchQuery, books=session["books"])    return render_template("index.html")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614296.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号