Passing variable database name in psycopg2's execute()

This is what I have:

    db_name = 'temp_test_database'
    conn.set_isolation_level(0)
    cursor.execute('DROP DATABASE IF EXISTS {}'.format(db_name))

This functionality works and does what I expect, but violates the parameter passing rule.

I have looked at SQL string composition documentation, but this doesn't work with database names. It wraps it with "Identifier()", which breaks.

Is there "clean" way to dynamically set the database in a psycopg2 execute call?

1 answer

  • answered 2018-02-13 01:03 kindall

    Use psycopg2.sql.Identifier and compose the SQL statement like so:

    from from psycopg2 import sql
    
    cursor.execute(sql.SQL("drop database if exists {}")
        .format(sql.Identifier(db_name)))
    

    The whole linked documentation page is worth a read.