Connecting QGIS, SpatiaLite and Python?
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
# Import QtSql function(s)
from PyQt4.QtSql import QSqlDatabase
# Get selected layer
layer = iface.activeLayer()
# Get file path
uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
# Create DB connexion to do SQL
db = QSqlDatabase.addDatabase("QSQLITE");
# Reuse the path to DB to set database name
db.setDatabaseName(uri.database())
# Open the connection
db.open()
# query the table
query = db.exec_("""select * from your_table""")
# Play with results (not efficient, just for demo)
while query.next():
values = []
record = query.record()
for index in range(record.count()):
# We exclude the geometry to join attributes data
if not isinstance(record.value(index), QByteArray):
values.append(str(record.value(index)))
print ';'.join(values)
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
with QSPATIALITE
.
Then you can see if extension has been loaded with:
query = db.exec_("""SELECT sqlite_version(), spatialite_version()""")
query.next()
print query.value(0), query.value(1)
If it's just displaying the layer from Python
If you want to add the layer, don't forget after
vlayer=QgsVectorLayer(uri.uri(), display_name, 'spatialite')
to add it with:
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
A shortcut to do the same operation in one is:
iface.addVectorLayer(uri.uri(), display_name, 'spatialite')
uri.setDataSource(schema, table, geom_column,"pk=1")
The 4th parameter (optioonal) in setDataSource is a sql WHERE