The following works fine:
conn = psycopg.connect(self.conn.params.conn_str)
cur = conn.cursor()
cur.execute("""
SELECT 2, %s;
""", (1,),
)
But inside a DO
:
cur.execute("""
DO $$
BEGIN
SELECT 2, %s;
END$$;
""", (1,),
)
it causes
psycopg.errors.UndefinedParameter: there is no parameter $1
LINE 1: SELECT 2, $1
^
QUERY: SELECT 2, $1
CONTEXT: PL/pgSQL function inline_code_block line 3 at SQL statement
Is this expected?
2
Answers
Yes, because anonymous code blocks don’t accept parameters:
This might work as a workaround:
You can also use
PERFORM
instead ofSELECT ... INTO
if you don’t need to store the result:This uses the sql module of
psycopg
to build a dynamic SQL statement using proper escaping.DO
can’treturn
anything so you will not get any result from the function.