I’m trying to formulate the right query to select records that each have a category:
drop table if exists entries;
create table entries (
id integer primary key autoincrement,
title string not null,
text string not null,
pub_date integer,
category string not null);
I read the sqlite documentation and I still can’t figure out why I get :”no such column:Music” Where music is the dummy category.
Here's the function:
@app.route('/<category_name>')
def show_entries(category_name):
cur = g.db.execute('select id,title, text,pub_date,category from entries where category
=' +category_name)
entries = [dict(id=row[0], title=row[1], text=row[2],
pub_date=row[3],category=row[4]) for row in cur.fetchall()]
return render_template('show_entries.html', entries=entries)
Thanks for helping me out!
There are a number of problems with your code but the most basic one is that your final SQL statement does not place quotation marks around the value of category_name as required for strings in SQL (and most other languages).
What you are sending to SQLite is:
and it should be:
However, you should never build SQL statements by concatenating strings together since that exposes you to the possibility that a sneaky person (or ‘bot) put something into one of those strings that will destroy your database.
Instead, you should do this:
which is called a parameterized query. In this case, the database will make sure that category_name is handled properly as a piece of string data rather than (potentially) part of the SQL statement.