RoperMaps
RoperMaps

Reputation: 123

removing quotes when interpolating query value in psycopg2

Connected to this question, but I'm missing something.

When I run the following

table_name = 'my_schema.my_table'
cur.execute(sql.SQL('SELECT col1, col2 FROM {}').format(sql.Identifier(table_name)))

The query that is sent to the database is

SELECT col1, col2 FROM "myschema.myname"

And I get the error:

"relation "myschema.myname" does not exist"

I want the query to be

SELECT col1, col2 FROM myschema.myname

When I pass this directly to cur.execute I don't have a problem.


If it is of help I connect to the database following this tutorial using a .ini file which in my case looks like:

[postgresql]
host=ip_no_of_host
database=name_of_db
user=username
password=password

Upvotes: 2

Views: 1301

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125444

schema_name = 'my_schema'
table_name = 'my_table'
cur.execute(sql.SQL('SELECT col1, col2 FROM {}.{}').format(
    sql.Identifier(schema_name), sql.Identifier(table_name)
    )
)

or just

table_name = 'my_table'
cur.execute(sql.SQL('SELECT col1, col2 FROM my_schema.{}').format(
    sql.Identifier(table_name)
    )
)

Upvotes: 2

Related Questions