-2

I am trying to create a SQL query in a python program and I want to pass in my session variable. The session variable contains the logged in user for the program. I am having some syntax issues.

query = "SELECT * FROM following WHERE following.username == 'flask.session['user']' "

Here is my error:

sqlite3.OperationalError: near "user": syntax error

I am not sure how to fix this. Help would be greatly appreciated.

1
  • 1
    I don't use Flask so a guess based on common errors: cursor.execute("SELECT * FROM following WHERE username = ?", (flask.session['user'],)) Commented Jan 20, 2018 at 20:26

2 Answers 2

0

roganjosh fixed the issue.

Use:

cursor.execute("SELECT * FROM following WHERE username = ?", (flask.session['user'],))
Sign up to request clarification or add additional context in comments.

3 Comments

On a high level (i.e. not too specific), do you know what I did there? It's one thing to have working code, it's another to understand why it works so I want to be sure you understand the changes I made.
This is parameter substitution, right?
It's a parameterized query which will help against SQL injection. Since you only bind a single variable (which could be a string) you should always supply the value as a tuple (hence (flask.session['user'],)) otherwise it will try to unpack your value character-by-character.
-1

If you know that session['user'] is a string, than try this:

query = "SELECT * FROM following WHERE following.username == '%s' " %(session['user'])

You can use, %s for string, %i for integer...

1 Comment

This is very bad advice; it uses string formatting and leaves the user more exposed to SQL injection. There is no reason at all not to use a parameterized query for this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.