[GIS] How to add non spatial sqlite table to map using python in qgis

pluginspyqgispythonqgis

Is it possible to load pure sqlite 2.0 (without spatial extension) table into qgis using python? I would like to get the same result as in the case of using Add Vector Layer -> All files.
I have already modified this example http://www.qgis.org/pyqgis-cookbook/loadlayer.html
but it doesn't work in my case.
Can someone help me?
I use in the python console this code:

>>> db = r'c:\Program Files (x86)\Quantum GIS Lisboa\data\base.db'
>>> uri = QgsDataSourceURI()
>>> uri.setDatabase(db)
>>> schema = ''
>>> table = 'table'
>>> geom_column = ''
>>> uri.setDataSource(schema, table, geom_column)
>>> display_name = 'table'
>>> vlayer = QgsVectorLayer(uri.uri(), display_name, 'sqlite')
>>> QgsMapLayerRegistry.instance().addMapLayer(vlayer)
<qgis.core.QgsVectorLayer object at 0x0CFA08A0>

i also tried with 'spatialite' in vlayer. When I use Add vector layer i can see result table in the TOC. Using this code I can't display table in table of contents. I think the reason of my trouble is trivial, but I have no idea what I should do to see my table

Best Answer

If you are able to add a layer manually (Add Layer Dialog), you can get from it all the information needed to add it again via python.

Select the layer in the TOC

l = qgis.utils.iface.activeLayer()
p = l.dataProvider()

key = l.providerType()
uri = p.dataSourceUri()

QgsMapLayerRegistry.instance().addMapLayer( QgsVectorLayer( uri, 'layer', key ) )

In your case the key is 'spatialite'