2

I want to search a mysql table for rows where the specified column has a particular value. For example, given the input string memory=2048 it will search for the rows that have "2048" as the value of memory column and it will print them.

This is code that I have tried but it print outs nothing.

input = input()
tag = input.split("=")
desc = tag[1]
tag = tag[0]

mycursor = mydb.cursor()
sql = "(SELECT * FROM comp WHERE %s LIKE %s)"
val = (tag, desc)
mycursor.execute(sql, val)
res = mycursor.fetchall()
for x in res:
    print(x)

Secondly I tried this code to see where is the problem :

input = input()
tag = input.split("=")
desc = tag[1]
tag = tag[0]

mycursor = mydb.cursor()
sql = "(SELECT * FROM comp WHERE memory LIKE '2048')"
mycursor.execute(sql)
res = mycursor.fetchall()
for x in res:
    print(x)

It gives the desired output. So my problem is when I am trying to get the column name with %s it comes as 'memory' and It couldn't finds it, since the name of the column is memory. Is there a way to get rid of the '' chars ?

confirmation of inputs

Nickolay
  • 31,095
  • 13
  • 107
  • 185
Triath
  • 31
  • 1
  • 9

1 Answers1

1

Looking at the mysql.connector's execute() documentation it appears to use %s as placeholders for bind parameters.

So your execute("SELECT * FROM comp WHERE %s LIKE %s", ("memory", "2048")) call ends up running like the following SQL:

SELECT * FROM comp WHERE 'memory' LIKE '2048'

obviously returning 0 rows.

You need to put the literal column name into the query text before invoking execute():

sql = "SELECT * FROM comp WHERE %s LIKE %s" % (tag, "%s")
# =>  "SELECT * FROM comp WHERE memory LIKE %s"
mycursor.execute(sql, (desc, ))
Nickolay
  • 31,095
  • 13
  • 107
  • 185
  • It gives this error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1 – Triath Aug 15 '19 at 09:26
  • Sorry, you have to write it as `execute(sql, (desc, ))` https://stackoverflow.com/questions/44267501/mysql-connector-you-have-an-error-in-your-sql-syntax-near-s-at-line-1 - updated the answer – Nickolay Aug 15 '19 at 09:30