4

I have different qgis project with some layer and their datasource like ../my_path/my_file.shp. I need to insert this shp file to a remote db. For do it i use shapefile from PGeo module and it's work fine. But i need change layer datasource in qgs project with dbname= , host etc where schema_name is a name of qgis project, table_name is a layer id, and i need to maintain all layer's property. I tried to use:

 uri = QgsDataSourceURI()
 uri.setConnection("localhost", "5432", "mydb", "postgres", "postgres")
 uri.setDataSource(str(schema_name),str(layer.id()),'the_geom')
 layer = QgsVectorLayer(uri.uri(), str(layer.id()), "postgres")
 QgsMapLayerRegistry.instance().addMapLayer(layer)
 layer.reload()
 print layer.source()
 if not layer.isValid():
    print "Layer is not valid"
 project.write(QFileInfo(str(dir)+'/'+project_name))

But i always got "Layer is not valid" and nothing is changed on my qgis project. Is there another way to change layer datasource and save changes to the project? I see this solution but it doesn't work for me

  • in uri.setDataSource(str(schema_name),str(layer.id()),'the_geom') instead of layer.id() (that is something internal to qgis, use the table name of your db. – Luigi Pirelli Apr 28 '15 at 8:12
  • str(layer.id()) is my table name. – sasha Apr 28 '15 at 8:59
  • are you sure? layer.id() if layer is a QgsVectorLayer return the layer name plus a random number! – Luigi Pirelli Apr 28 '15 at 9:28
  • yes,when i export my shp file into postgres db i do it like schema_name - my qgis project name, and table_name like internal id of layer i export. – sasha Apr 28 '15 at 9:35
  • I use this comand for export my shp file to db: shapefile._import_shapefile(host='localhost',port = 5432,dbname='mydb',user='postgres',password='postgres',shapefile = layer.source(),table =str(schema_name+"."+layer.id()),overwrite = 'false',encoding='UTF8') – sasha Apr 28 '15 at 9:51
3

It's seem that's uri is a key sensitive, so I solved a problem with:

table_name = table_name.lower()
schema_name = schema_name.lower()
uri.setDataSource(schema_name,table_name,"the_geom", '', 'gid')

After this change layer.isValid() return true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.