1

I have a SQLite database that I'd like to search using Python variables as in:

cur.execute("SELECT * FROM list WHERE InstitutionName=Variable")

Ideally this would allow me to return each row as a list to a larger list that contains all the rows a user is searching for. I realize what I have above is pseudocode. How could I actually write it?

Molly Walters
  • 1,631
  • 3
  • 13
  • 7

3 Answers3

17

I think that you want to use the parameter substitution feature:

cur.execute("SELECT * FROM list WHERE InstitutionName=?", (Variable,))

There's more documentation in the actual execute command and in the 4th example code box on the sqlite3 docs page.

Note that you should explicitly not use the % or format function as this is susceptible to injection attacks:

# NEVER DO THIS
cur.execute("SELECT * FROM list WHERE InstitutionName='%s'" % (Variable,))
Xymostech
  • 9,710
  • 3
  • 34
  • 44
2

If you want to display multiple records from database then you can use the (LIKE) keyword in your sql query:

("SELECT * FROM TABLENAME WHERE name LIKE'%?%'",(Variable,))
Jawad Saqib
  • 95
  • 1
  • 3
  • 10
0

If you want to use LIKE

cur.execute("SELECT * FROM list WHERE InstitutionName like '%'||?||'%'", (Variable,))
Punnerud
  • 7,195
  • 2
  • 54
  • 44