-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
    I don't use Flask so a guess based on common errors: `cursor.execute("SELECT * FROM following WHERE username = ?", (flask.session['user'],))` – roganjosh Jan 20 '18 at 20:26

2 Answers2

0

roganjosh fixed the issue.

Use:

cursor.execute("SELECT * FROM following WHERE username = ?", (flask.session['user'],))
  • 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. – roganjosh Jan 20 '18 at 20:35
  • This is parameter substitution, right? – CuriousProgrammer70184 Jan 20 '18 at 21:41
  • 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. – roganjosh Jan 20 '18 at 21:49
-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...

Abdullah
  • 131
  • 1
  • 10
  • 1
    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. – roganjosh Jan 20 '18 at 20:49