0

Suppose a simple query in python as follows. The python code reads a "new city" from a user. The question is how to update the query by appending a list of cities (e.g., 'city1', 'city2', 'city3') to the where clause in the query.

mycursor = mydb.cursor()

sql = "select * FROM my_table 

WHERE (city = 'Seattle') 
or (city = 'Portland')"

mycursor.execute(sql)

mydb.commit()

desired sql script

mycursor = mydb.cursor()

sql = "select * FROM my_table 

WHERE (city = 'Seattle') 
or (city = 'Portland')
or (city =  'city1') 
or (city = 'city2)
or (city ='city3')"

mycursor.execute(sql)

mydb.commit()
1
  • Is there a reason you're not using WHERE city IN ('Seattle', 'Portland', ...)? Commented Jun 30, 2021 at 20:12

2 Answers 2

2

Use city IN (...) rather than multiple city = operations. Then you can build the list of placeholders dynamically and replace them using parameters.

cities = ['Seattle', 'Portland', 'city1', 'city2', 'city3']
placeholders = ','.join(['%s']*len(cities))
sql = f'SELECT * FROM my_table WHERE city IN ({placeholders})'
mycursor.execute(sql, cities)
Sign up to request clarification or add additional context in comments.

Comments

0

The solution would require string manipulation like so (assuming u take input to a variable newCity):

mycursor = mydb.cursor()
sql = "select * FROM my_table WHERE (city = 'Seattle') or (city = 'Portland')"

#put in for loop for as long as ud like 
newCity = input("insert new city")
sql = sql + " or (city = \'" + newCity + "\')"

mycursor.execute(sql)
mydb.commit()

Comments

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.