Search code examples
pythonmysqlpymysql

Using WHERE in query PyMySQL


I am trying to create a program where a user can enter an operator i.e. <> or = and then a number for a database in pymysql. I have tried a number of different ways of doing this but unfortunately unsuccessful. I have two documents with display being one and importing display into the other document.

Docuemnt 1

def get_pop(op, pop):
if (not conn):
    connect();

query = "SELECT * FROM city WHERE Population %s %s"


with conn:
    cursor = conn.cursor()
    cursor.execute(query, (op, pop))
    x = cursor.fetchall()
    return x

Document two

 def city():
     op = input("Enter < > or =: ")
     population = input("Enter population: ")
     pop = display.get_pop(op, population)
     for p in pop:  
     print(pop) 

I am getting the following error.

pymysql.err.ProgrammingError: (1064,......

Please help thanks


Solution

  • After checking that op indeed contains either "<>" or "=" and that pop indeed contains a number you could try:

    query = "SELECT * FROM city WHERE Population " + op + " %s";
    

    Beware of SQL injection.

    Then

    cursor.execute(query, (pop))