connerito
connerito

Reputation: 1

MySQL ProgrammingError on simple SELECT query with user-provided input

def search():
    searc = input("Enter the name you want to search: ")
    s = (searc)
    mycursor.execute("SELECT * FROM studen WHERE Name = {}".format(s))
    for i in mycursor:
        print(i)

I'm trying to fetch data from the studen table where name is entered by the user.

Here is the error that I'm getting:

ERROR: mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'ayush' in 'where clause'

Upvotes: 0

Views: 66

Answers (1)

Chris
Chris

Reputation: 136987

The immediate problem is that your query is missing quotes. The string you get with .format() looks like this, assuming ayush is your input:

SELECT * FROM studen WHERE Name = ayush

But it needs to look like this:

SELECT * FROM studen WHERE Name = 'ayush'

However, you shouldn't be using .format() at all since it leaves you wide open to SQL injection.

This is the proper way to parametrize a query using mysql.connector:

mycursor.execute("SELECT * FROM studen WHERE Name = %s", (s,))

Note also that I have used (s,) instead of (s) here to get a tuple of one element.

Upvotes: 1

Related Questions