1

i have a sample query template to accept dynamic parameters to execute:

ps_conn = psycopg2.connect(...)
ps_cursor = ps_conn.cursor()
ps_cursor.execute('''
    SELECT *
    FROM "posts"
    ) ORDER BY "posts"."rate" %s, "posts"."date_created" ASC LIMIT 1
    ''', ["DESC"])

as you can see i wanna pass DESC dynamically to orderby the results , but the above code keep throwing the error InvalidSchemaName

schema "posts" does not exist LINE 11:) ORDER BY "posts"."rate" 'DESC',

it passes the DESC as 'DESC' to the sql .

any opinion how to perform this functionality so i can pass ordering type dynamically?

3 Answers 3

1

Update your query like this and try:

ps_cursor.execute('''
SELECT *
FROM "posts"
) ORDER BY "posts"."rate" {0}, "posts"."date_created" ASC LIMIT 1
'''.format("DESC"))
Sign up to request clarification or add additional context in comments.

1 Comment

yeah i realized when we use string formatting the passed string will not get quotation around it .
1

I would instead create a separate variable and code as follows:

ps_conn = psycopg2.connect(...)
ps_cursor = ps_conn.cursor()

# you may add a condition to use DESC or not
dynamic_sort = 'DESC'
ps_cursor.execute('''SELECT *
                     FROM posts
                     ORDER BY rate %s, date_created ASC 
                     LIMIT 1''',
                  (dynamic_sort))

Comments

0
ps_conn = psycopg2.connect(...)
ps_cursor = ps_conn.cursor()
ps_cursor.execute('''
    SELECT *
    FROM "posts"
    ORDER BY "posts"."rate" {order}, "posts"."date_created" ASC LIMIT %s
    '''.format(order='desc'),(1,))

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.