![](/img/trans.png)
[英]How can I query and get data from my sqlite database even when my search input have similar words that is apart from each other (not continuously)
[英]I query my sqlite database and got the result as [ ] (blank) even when my database has the data I tried to query
我查詢我的 sqlite 數據庫並得到結果為 [ ](空白),即使我的數據庫有我試圖查詢的數據。
所以我將我的 Python 文件與我的 SQLite 數據庫連接起來(它連接良好)並通過在 HTML 文件上使用 Jinja 語法顯示的表單查詢用戶輸入的數據:
import os and some other not important things
MYDIR = os.path.dirname(__file__)
SQLPATH = os.path.join(MYDIR, "..", "data.sqlite")
conn = _sqlite3.connect(SQLPATH, check_same_thread=False)
c = conn.cursor()
core = Blueprint('core', __name__)
@core.route('/', methods=['GET', 'POST'])
def index():
# Call a function to later use in creating the template
search = Blogsearch_form(request.form)
print(search.data)
if request.method == 'POST':
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(search.data) + '%',))
results = c.fetchall()
print(results)
return render_template('blog_search_result.html', results=results)
# return blog_search_results(search)
page = request.args.get('page',1,type=int)
many_posts = BlogPost.query.order_by(BlogPost.date.desc()).paginate(page=page, per_page=10)
return render_template('index.html', many_posts=many_posts, form=search)
您可以看到我在我的代碼中放置了 2 個打印件進行測試,下面是這些打印件的結果: print(search.data): {'search': 'New Life 3 check'} (New Life 3 check 是我的輸入輸入 HTML 表格)
打印(結果):[]
下面是我的 Blogsearch_form 的 python 文件:
from wtforms import Form, StringField
class Blogsearch_form(Form):
search = StringField('')
在我的 HTML 文件中顯示表格的部分:
<form class="form-inline my-2 my-lg-0 text-right" method=POST>
{{ render_field(form.search) }}
<input type=submit value=Search>
</form>
結果應顯示列 prolem_name 包含“New Life 3 check”字樣的行中的所有數據。 該行位於名為“blog_post”的表中,該表位於數據庫“data.sqlite”中。 但是,正如我在上面顯示的那樣,它給出了一個空白 [ ]。 我堅持了一段時間,如果你能幫助我,我將不勝感激。
謝謝!
我認為這條線應該是
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(search.search.data) + '%',))
代替
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(search.data) + '%',))
因為您試圖獲取字段的數據而不是整個表單。 另外,我建議您提供更具可讀性的變量名稱!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.