Forums

Attempting mysql SELECT using variable with no success

I have been trying to make this call to search mysql table for a variable in a certain column. I've had success with non-variables but this has been a frustrating endeavor. See an example below of what does not work:

cursor.execute("SELECT * FROM MYDATA WHERE mydescription LIKE ?", (WORD2SEARCH))

Can anyone assist as I am sure there is a simple explanation?

what's the error when you make that call?

ok-the error message I am getting is: mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use ……

It applies to the following attempts to find a word within a column (anywhere within the field):

cursor.execute("""SELECT * FROM CSVTEST where DESK = ?"""
values = (word2search4)

THIS GENERATES AN ERROR

 sql= "SELECT * FROM CSVTEST WHERE DESK = ? \
 VALUES ('%s')" % \
 (word2search4)
 cursor.execute(sql)

THIS GENERATES AN ERROR

cursor.execute("SELECT * FROM CSVTEST WHERE DESK LIKE '%s'" % symbol)

THIS GENERATES AN ERROR

 sql = """SELECT SKU FROM CSVTEST WHERE DESK LIKE '%s'""" %(symb)
cursor.execute(sql)

THIS GENERATES AN ERROR

HOW WOULD YOU FORMULATE AN SQL CALL FROM PYTHON TO SEARCH FOR A WORD WITHIN A TERM OR SENTENCE?

Thank you in advance.-JK

[edit by admin: formatting]

Try this:

cursor.execute("SELECT * FROM CSVTEST WHERE DESK LIKE %s", (symbol,))

Note the trailing comma after symbol -- it's important because it makes the argument a tuple. (symbol) on its own is identical to symbol without the brackets, because the brackets there are used for grouping (just like they would be in (symbol + othersymbol). The trailing comma tells Python that you want a one-element tuple containing symbol as its element.

These Python MySQL docs should also help.

Thank you for your response. Your select statement works but ONLY FOR A PERFECT MATCH. I need to find a string within a string (column). Any idea?

This should do it:

cursor.execute("SELECT * FROM CSVTEST WHERE DESK LIKE %s", ("%" + symbol + "%",))

no luck!! The error mesg is:

TypeError: cannot concatenate 'str' and 'tuple' objects

That sounds like you may have mistyped the command. That error would occur if you did this:

 :::python
cursor.execute("SELECT * FROM CSVTEST WHERE DESK LIKE %s", "%" + (symbol,) + "%")

Note that the brackets are in the wrong place. Could you double-check exactly what you're running?