1
votes
table = "tbl_" + platform + "_chks"
search = "%" + search + "%"

cur.execute('''SELECT check_id,check_name,%s, FROM %s WHERE %s LIKE %s;''', (field,table,field,search))

I'm getting the following error:

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 near ''tbl_linux_chks' WHERE 'check_name' LIKE '%test%'' at line 1)

2
You can't use parameters in table or field names like this - Sami Kuhmonen
is there no alternative? I'd rather not have to make redundant if/elif statements - Monie
You'll have to concatenate the values to the SQL string manually. And you'll have to make sure they're all handled by you so there's no possibility for injection - Sami Kuhmonen
I've edited my question with your suggestion (see above), still getting same error - Monie
You can't use %s for table or field names. Put the proper strings there. - Sami Kuhmonen

2 Answers

0
votes

%s query parameter placeholders can only be used for that, query parameters, not for identifiers like table or column names. When query parameters are used, strings are automatically quoted and escaped before inserted in a query, but quoting for table and column names is different.

MySQL uses single or double quotes for quoting values, but it uses backticks (`) for quoting identifiers.

For this to work correctly, you need to create the query first (using string formatting), then you can execute that query using query parameters:

# `field` and `platform` must not come from user input, or be validated!
table = "tbl_" + platform + "_chks"
query = ('SELECT check_id, check_name, `{0}` FROM `{1}` WHERE `{0}` LIKE %s'
         .format(field, table))
cur.execute(query, ("%" + search + "%",))

Make really sure that platform and fields do not come from user input, otherwise you'll have an sql injection vulnerability.

0
votes

Try this:

cur.execute("""SELECT check_id,check_name,{} 
               FROM tbl_{}_chks 
               WHERE {} LIKE '%%{}%%'
               """.format(field,platform,field,search))

The reason this driver developers separate arguments from query is security. So you should take care about the data in the variables before using this solution.