0

Im trying to pass a sql ( wich works perfectly if i run it on the client ) inside my python script, but i receive the error "not enough arguments for format string"

Following, the code:

sql = """
SELECT
  rr.iserver,
    foo.*, rr.queue_capacity,
    rr.queue_refill_level,
    rr.is_concurrent,
    rr.max_execution_threads,
    rr.retrieval_status,
    rr.processing_status
FROM
    (
        SELECT DISTINCT
            ip.package,
            it. TRIGGER
        FROM
            wip.info_package ip,
            wip.info_trigger it
        WHERE
            ip.service = it.service and
      ip.iserver = '%(iserver)s' and
      it.iserver = %(iserver)s'
        AND package = '%(package)s'
        UNION
            SELECT
                '%(package)s' AS package,
                TRIGGER
            FROM
                info_trigger
            WHERE
                TRIGGER LIKE '%(package)s%'
    ) AS foo,
    info_trigger rr
WHERE
    rr. TRIGGER = foo. TRIGGER
""" % {'iserver' : var_iserver,'package' : var_package}
dcon = Database_connection()
getResults = dcon.db_call(sql, dbHost, dbName, dbUser, dbPass)
# more and more code to work the result....

My main problem on this is how i can pass '%(iserver)s' , '%(package)s' correctly. Because usualy, when i select's or insert's on database, i only use two variables , but i dont know how to do it with more than two.

Thanks.

2 Answers 2

9

Don't build SQL like this using %:

"SELECT %(foo)s FROM bar WHERE %(baz)s" %
  {"foo": "FOO", "baz": "1=1;-- DROP TABLE bar;"}

This opens the door for nasty SQL injection attacks.

Use the proper form of your Python Database API Specification v2.0 adapter. For Psychopg this form is described here.

cur.execute("SELECT %(foo)s FROM bar WHERE %(baz)s",
  {"foo": "FOO", "baz": "1=1;-- DROP TABLE bar;"})
Sign up to request clarification or add additional context in comments.

Comments

8
WHERE
                TRIGGER LIKE '%(package)s%'

you have an EXTRA '%'

if you want the actual character '%', you need to escape with a double '%'.

so it should be

WHERE
                TRIGGER LIKE '%(package)s%%'

if you want to display a '%'

and

WHERE
                TRIGGER LIKE '%(package)s'

if you dont

2 Comments

You may also want to switch to using str.format(), as it's preferred over % in Python 3
@ernie thanks +1, i did not know that. i wonder if its cosmetic, or if there are some real reasons for this.

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.