0

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

1
  • 1
    You can't do this. You can't parameterize the operator, you'll need to .format() (or similar) that in to the string Commented Apr 11, 2019 at 22:42

2 Answers 2

3

You can't do this. Parameterization works for values only, not operators or table names, or column names. You'll need to format the operator into the string. Do not confuse the %s placeholder here with Python string formatting; MySQL is awkward in that it uses %s for binding parameters, which clashes with regular Python string formatting.

The MySQL %s in a query string escapes the user input to protect against SQL Injection. In this case, I set up a basic test to see if the operation part submitted by the user was in a list of accepted operations.

def get_pop(op, pop):
    query = "SELECT * FROM city WHERE Population {} %s" # Add a placeholder for format

    with conn: # Where does this come from?
        cursor = conn.cursor()
        if op in ['=', '!=']:
            cursor.execute(query.format(op), (pop,))
            x = cursor.fetchall()
            return x

You'll want to come up with some reasonable return value in the case that if op in ['=', '!='] is not True but that depends entirely on how you want this to behave.

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

1 Comment

Thanks for your help :)
1

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))

1 Comment

Thanks for your help J.R.

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.