如何从 html 获取 USER 输入并使用 Python 在数据库中搜索它

Posted

技术标签:

【中文标题】如何从 html 获取 USER 输入并使用 Python 在数据库中搜索它【英文标题】:How to get USER input from html and search for it in databse with Python 【发布时间】:2019-11-19 18:17:09 【问题描述】:

我有一个数据库,我想用这个 html 在其中搜索

       <form action="/question/search" method="POST">
           <input id="search" type="text" placeholder="Search.." name="search">
           <button id="search" type="submit">&#x1F50D;</button>
      </form>

我在我的函数中获取数据

@app.route("/question/search",methods=["POST"])
def search():
    search_result = request.form.get("search")
    story = data_handler.get_search_result(search_result)
    return render_template('search_resoult.html', stories=story)

但我只是无法弄清楚我尝试过的 SQl:

@database_common.connection_handler
def get_search_result(cursor,item):
    my_sql = "SELECT * FROM question WHERE title LIKE %s OR message LIKE %s"
    my_resoult = (item)
    cursor.execute(my_sql, my_resoult)
    resoult = cursor.fetchall()
    return resoult

我只想获取标题或消息中包含 my_result 的所有数据。 它总是给我这个错误:

TypeError: not all arguments converted during string formatting

【问题讨论】:

【参考方案1】:

问题是您的查询需要解压缩 2 个值,但您只提供一个 (item)。如果你想使用item作为title LIKEmessage LIKE的条件,你应该扩展my_resoult

my_resoult = (item, item) 

【讨论】:

以上是关于如何从 html 获取 USER 输入并使用 Python 在数据库中搜索它的主要内容,如果未能解决你的问题,请参考以下文章