Skip to content
Advertisement

String table name not working in a query with psycopg2

I would like to generate dynamic queries with variables for column names and table name. This is my code:

I get the following error:

psycopg2.errors.UndefinedTable: relation “d1dbforest.interface.v_monitoring_ind34a4” does not exist LINE 1: select “country”,”year”,”data”,”use” from “d1dbforest.interf…

I noticed that in pgAdmin4 I can run

but not

So, it looks like I cannot use a string table name in the query. Maybe it is also worth to note that I am connecting to a view, not a table. Can anyone suggest a way to inject a table name as a variable to a query?

Thanks.

Advertisement

Answer

when you quote something,it is considered as one object while “d1dbforest.interface.v_monitoring_ind34a4” is referring to 3 objects , database name , schema name and view name :

so you need to quote them separately: "d1dbforest"."interface"."v_monitoring_ind34a4"

so:

then you have to specify it in the identifier :

reference: https://www.psycopg.org/docs/sql.html#module-psycopg2.sql

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement