[GIS] Deleting vector layer from GeoPackage using PyQGIS

deletegeopackagepyqgis-3pythonvector

Programmatically I have added the vector layers to an existing GeoPackage in QGIS 3.2 using Python. Similarly, I would like to delete a layer from the existing GeoPackage using Python code. But there is no example/help found online.

Here is my code to add the selected layers to an existing Geo package:

layer = self.iface.activeLayer() 
layer.startEditing()
gpkgPath='D:/AA/Layer/sample_gpkg'
options = QgsVectorFileWriter.SaveVectorOptions()
options.actionOnExistingFile =QgsVectorFileWriter.CreateOrOverwriteLayer   
options.layerName = 'test'
_writer=QgsVectorFileWriter.writeAsVectorFormat(layer,gpkgPath,options)

enter image description here

Best Answer

You can use the SpatiaLite execute SQL tool and drop table:

gpkg = '/home/bera/GIS/Data/testdata/overlaps.gpkg'
lyr = 'overlaps'

processing.run("native:spatialiteexecutesql", {'DATABASE':'{0}|layername={1}'.format(gpkg, lyr),
    'SQL':'drop table {0}'.format(lyr)})

enter image description here