Create Views in the Database from Role

1

I'm developing a simple application where you'll need to create a PostgreSQL view via Python function. So far it seems like a simple code, but what I did it does not create views in the database and also does not present an error to my despair.

The function is:

 def cria_view(self):
    cursor = self.connectBanco()    
     sql = "CREATE OR REPLACE VIEW espacial.teste AS SELECT *FROM espacial.fx_pedestre;"

     cursor.execute(sql)

Here I call the method:

instancia_sql.cria_view()

With this same SQL I create the view by the Query of Postgresql, but the function in Python does not create, but also does not give error. Does anyone know why? Am I missing something?

    
asked by anonymous 16.10.2016 / 17:18

1 answer

0

You may need to use the MySQLConnection.commit to confirm the current transaction and save the changes.

conexao = MySQLdb.connect(host = "localhost", user = "root", passwd  = "pass", db = "dbname")
cursor = self.connectBanco()    

sql = "CREATE OR REPLACE VIEW espacial.teste AS SELECT * FROM espacial.fx_pedestre;"
cursor.execute(sql)

conexao.commit()

Note : Assuming that the self.connectBanco function returns an object cursor ", you can not use cursor.commit() , if you prefer to change this, in function self.connectBanco do something like this:

def connectBanco(self):
    conexao = MySQLdb.connect(host = "localhost", ...)

    # Códigos...
    return conexao

In the cria_view method you can do this:

def cria_view(self):
    conexao = self.connectBanco()
    cursor  = conexao.cursor()

    sql = "CREATE OR REPLACE VIEW espacial.teste AS SELECT * FROM espacial.fx_pedestre;"

    cursor.execute(sql)
    conexao.commit()
    
16.10.2016 / 18:07