Reputation: 338
I query my sqlite database and got the result as [ ] (blank) even when my database has the data I tried to query.
So I connected my Python file with my SQLite database (it connects fine) and query the data the user input through a form that is shown through using Jinja syntax on the HTML file:
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)
You can see that I put 2 prints inside my codes to test and here is the results of those prints: print(search.data): {'search': 'New Life 3 check'} (New Life 3 check is the input I type in the HTML form)
print(results): [ ]
Below is my Blogsearch_form's python file:
from wtforms import Form, StringField
class Blogsearch_form(Form):
search = StringField('')
The part that shows the form on my HTML file:
<form class="form-inline my-2 my-lg-0 text-right" method=POST>
{{ render_field(form.search) }}
<input type=submit value=Search>
</form>
The results should show all the data in the row that has the column prolem_name that contain words of "New Life 3 check". This row is inside a table called "blog_post", which is in the database "data.sqlite". However, as I show above, it give out a blank [ ]. I stuck on this for a while and I would greatly appreciate if you could help me.
Thank you!
Upvotes: 2
Views: 105
Reputation: 1383
I think this line should be
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(search.search.data) + '%',))
instead of
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(search.data) + '%',))
because you are trying to get the data of a field instead of the whole form. Also I would suggest you to provide more readable names of the variables!
Upvotes: 1