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?

schema=' '
table ='ambi'
geom_column= 'geom'
uri.setDataSource(schema, table, geom_column)
vlayer=QgsVectorLayer(uri.uri(), display_name, 'spatialite')

Finally I have put this:

uri = QgsDataSourceURI()
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");
query=db.exec_("""select * from PV where pk=1 """)

But It adds the complete shape and I want only add, the PV with pk=1. Could you tell me why it is?

  • 1
    Try forward slashes in your database path.
    – underdark
    Oct 26, 2015 at 0:00
  • Or try putting an 'r' in front of your path like this: r'C:\Users\pr\Desktop\GIS.sqlite'
    – Fezter
    Oct 26, 2015 at 5:55

2 Answers 2


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
# Open the connection
# 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):
    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()""")
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:


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

  • It might help to provide some more context, or a reference.
    – BradHards
    Aug 23, 2016 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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