I am trying to connect with python code, QGIS and Spatialite, to do SQL query. I have read some tips and I tried with this code, but no add anything.
Any Idea?
uri=QgsDataSourceURI()
uri.setDatabase('C:\Users\pr\Desktop\GIS.sqlite')
schema=' '
table ='ambi'
geom_column= 'geom'
uri.setDataSource(schema, table, geom_column)
display_name=('prueba')
vlayer=QgsVectorLayer(uri.uri(), display_name, 'spatialite')
Finally I have put this:
uri = QgsDataSourceURI()
uri.setDatabase('C:/Desktop/GIS.sqlite')
schema = ''
table = 'PV'
geom_column = 'geom'
uri.setDataSource(schema, table, geom_column)
display_name = 'PV'
vlayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')
db = QSqlDatabase.addDatabase("QSQLITE");
db.setDatabaseName(uri.database())
db.open()
query=db.exec_("""select * from PV where pk=1 """)
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
But It adds the complete shape and I want only add, the PV with pk=1.
Could you tell me why it is?
Best Answer
I have a doubt about your expectations
If it's doing SQL query on a SQlite/Spatialite DB within QGIS
Select the layer that use SQlite as a source, then do
It was mainly inspired by this topic but applied to SQLite/Spatialite
To really use Spatialite (in fact an extension you load in SQLite) and not only SQLite, you can replace
QSQLITE
withQSPATIALITE
. Then you can see if extension has been loaded with:If it's just displaying the layer from Python
If you want to add the layer, don't forget after
to add it with:
A shortcut to do the same operation in one is: