Search code examples
pythonpostgisqgis

PyQGIS - Adding layer from PostGis database and work with it in QGIS interface


I try to add from my db postgis to my QGIS interface a table, I'm using a script with the good parameters. But my problem is when I run my function my QGIS bugs and close.

from qgis.core import *
from qgis.core import QgsProject
from PyQt5.QtCore import QFileInfo
from qgis.core import QgsVectorLayer, QgsDataSourceUri
from qgis.utils import *

def run_script(iface):
   uri = QgsDataSourceUri()
   uri.setConnection("localhost", "5432", "Base_test", "user", "passeword")
   uri.setDataSource("public", "BPE", "geom")

   layer = QgsVectorLayer(uri.uri(), "bpe", "user")
   if not layer.isValide():
       print("Layer %s did not load" %layer.name())  
   QgsProject.instance().addMapLayer(layer)

it say me that the layer did not load. and QGIS need to be restarted after that.

can someone help me please.

I'm using QGIS 3.10


Solution

  • Try this code:

       from qgis.core import *
       from qgis.core import QgsProject
       from PyQt5.QtCore import QFileInfo
       from qgis.core import QgsVectorLayer, 
       QgsDataSourceUri
       from qgis.utils import *  
    
       def run_script(iface):
       uri = QgsDataSourceUri()
       uri.setConnection("localhost", "5432", "Base_test", 
       "user", "passeword")
       uri.setDataSource("public", "BPE", "geom")
    
       layer = QgsVectorLayer(uri.uri(), "bpe", "postgres")
       if not layer.isValid():
           print("Layer %s did not load" %layer.name())  
       QgsProject.instance().addMapLayer(layer)
    
       run_script()
    
    1. You made a spelling mistake:if not layer.isValide()-->if notlayer.isValid()
    2. You need to specify the provider (postgres in this case) layer = QgsVectorLayer(uri.uri(), "bpe", "user")--> layer=QgsVectorLayer(uri.uri(), "bpe", "postgres")
    3. Run/Call the function (you just defined it): run_script()

    Check the Documentation: https://qgis.org/pyqgis/3.0/core/Vector/QgsVectorLayer.html

    Cheers