Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have MS SQL Server 2008 R2 database. How to add MS SQL Table using python console in QGIS?

share|improve this question
1  
Welcome to gis.SE. To help us provide a better answer, can you expand your question a little (just click edit, above) to tell us more about your specific scenario - database schema, table structure (especially the geometry) and whether you are doing this on the local machine or to a remote server? –  BradHards Apr 6 '13 at 6:55
    
My database is on the local machine. I have a table with 2 fields:id (int) and shape(geography). –  Mari Apr 6 '13 at 13:51
    
Mari: Its easier to understand if you actually update the question, rather than just putting the details in comments. You can amend the question text by clicking "edit" below the question. –  BradHards Apr 6 '13 at 23:44

1 Answer 1

Each data provider has its URI and its provider key. Once added via User Interface, it's easy to collect them and use them from the console.

Enter this statement in your python console, to collect the URI and key for all map layers:

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    uri = layer.dataProvider().dataSourceUri()
    providerKey = layer.dataProvider().name()
    print("URI:\n%s\nKey:\n%s\n" % (uri, providerKey))

to create a new map layer based on this information:

Vector Layer

vl = QgsVectorLayer( uri, 'MyLayerName', providerKey )
QgsMapLayerRegistry.instance().addMapLayers( [vl] )

Raster Layer

rl = QgsRasterLayer( uri, 'MyLayerName', providerKey )
QgsMapLayerRegistry.instance().addMapLayers( [rl] )

The key for MS SQL is 'mssql'

The uri follow the QgsDataSourceURI standard, which has an example in the PyQGIS cookbook chapter Loading Layers, Vector Layers. MS SQL works analogue to postgres.

The above example duplicates just one layer, but prints the necessary information to add each of them and gives an idea about the principle.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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