0

I have a table with following columns

command_create_table = """CREATE TABLE if not exists place (
name VARCHAR(100),
lat DOUBLE(100, 10),
lng DOUBLE(100,10),
vicinity VARCHAR(100),
typeOfPlace VARCHAR(100));"""

This typeOfPlace column can contain types such as food, restaurant, museum etc. Now based on an user input which I capture in a variable called typeVar that indicates a specific value in typeOfPlace column, I want to retrieve items. So I have below code:

connection = sqlite3.connect("places.db")

cursor = connection.cursor()      
cursor.execute("SELECT * from place WHERE typeOfPlace=typeVar")
ans= cursor.fetchall()

But I am getting error

cursor.execute("SELECT * from place WHERE typeOfPlace=typeVar")
OperationalError: no such column: typeVar

What am I missing? Please suggest.

2 Answers 2

3

Try:

cursor.execute("SELECT * from place WHERE typeOfPlace=?", (typeVar,))

The trailing comma after typeVar might look odd, but params expects a sequence, and adding the trailing comma makes the value passed a tuple of length 1.

Never use string formatting to pass in values to an SQL query. Bad things can happen if the variable contains SQL syntax. Look up SQL injection attacks for more details on why you should not do this. Passing parameters separately as I’ve done here is the way to go.

Sign up to request clarification or add additional context in comments.

4 Comments

getting error "SyntaxError: EOL while scanning string literal"
@nad I think I had the wrong type of quotation mark, edited if you can try again please.
getting a different error now "TypeError: execute() takes no keyword arguments" pointing to the same line
@nad I’ve edited again and think it’s right this time. Third time lucky...
0

The issue is that you're checking for the literal string "typeVar", not the user input.

Instead of

cursor.execute("SELECT * from place WHERE typeOfPlace=typeVar")

try:

cursor.execute("SELECT * from place WHERE typeOfPlace={}".format(typeVar)).

4 Comments

so now if my variable input is "food", it is telling me "no such column as food". Clearly I am not checking for column named food but the rows where "typeOfPlace" column has value "food".
If you do select * from place; what output do you get?
it outputs the entire table
And the table has the entries for 'food', etc.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.