I can run a SQL in a PostGIS Table to load the query in QGIS3.16 (running Ubuntu Desktop 20.04) like this:
uri = QgsDataSourceUri()
uri.setConnection("localhost", "5432", "dbname", "username", "password")
print("Connection Successful")
nb = 1050130
fields = '*'
sql ='''(SELECT {} FROM montebelodosul.cadastro_urbano_montebelodosul_p WHERE numero_cadastro = {})'''.format(fields,nb)
# Retrieve the query table
uri.setDataSource('', f'({sql})', 'geom', '', 'id')
# add the layer to the canvas
pg_layer = QgsVectorLayer(uri.uri(False), "queryLayer", "postgres")
QgsProject.instance().addMapLayer(pg_layer)
I am not using Psycopg2. Would anyone give me an insight or point me in a direction on how to run an UPDATE or an INSERT on the table using PyQGIS before running a SELECT as shown above?