0

I try to execute the following query as a prepared statement:

self.cursor.execute("select distinct ? from isap.tn_documentation where ? = '?' and  ? <> ''", attribute2, attribute1, i.text(0), attribute2)

After execution i get the following error:

The SQL contains 3 parameter markers, but 4 parameters were supplied', 'HY000

3
  • 1
    You shouldn't have to single-quote the text literal in the predicate. That may be the issue. Commented Jan 20, 2020 at 22:06
  • Without the quotes, i will get a wrong result. Commented Jan 20, 2020 at 22:11
  • I don't think that's true. The prepare call goes to server and should obtain type information, the use of which should allow the client to bind the parameters correctly. (If I remember correctly) Commented Jan 20, 2020 at 22:18

1 Answer 1

2

You cannot pass column names as query parameters. You would need to concatenate the column names in the query string (while keeping the column values as parameters).

This should look like:

self.cursor.execute(
    "select distinct " 
        + attribute2 
        + " from isap.tn_documentation where " 
        + attribute1 + " = ? and " + attribute2 + " <> ''", 
    i.text(0)
)

Please note that doing so exposes your code to SQL injection: if your attributes input are coming from outside your code, this is a severe security breach. You would need to ensure that they do not contain malicious data (for example by checking the value of each attribute against a fixed list of allowed values: this should be quite easy since we are dealing with column names).

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

Comments

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.