3

I've got Python code on QGIS 3.12 that adds a MS SQL Server data layer to the map, but I need to add all of them.

uri = QgsDataSourceUri()

uri.setConnection(r"xx.xxx.xxx.xx\xxx", "xxxx", "xxx", "xxxx", "xxxx")

uri.setDataSource("000001","lcentro", "geom","")

uri.setSrid('31982')

vlayer = QgsVectorLayer(uri.uri(),"Roads","mssql")

QgsProject.instance().addMapLayer(vlayer)

So I can't figure out how to do it for all the geometry tables.

The Table

0
1

In order to make your code generalizable, you can code as follows:

from PyQt4.QtSql import * #for QGIS 3.x use instead PyQt5.QtSql
db = QSqlDatabase.addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("postgres");
db.setUserName("postgres");
db.setPassword("postgres");
db.open();
names=db.tables( QSql.Tables)
print names 
0

After some tries, I got it this way.

#table array
tabelas = (['quadras','lotes','edif','rdatrech','rdaramal'])

#setting conections to DB
dados = QgsDataSourceUri()
dados.setConnection(r"xxxxxx", "1433", "xxx", "user_xxx", "xxxxxx")

#search shapes on tables
for shape in tabelas:
    dados.setDataSource("your_db",shape, "geom","")
    vector_layer = QgsVectorLayer(dados.uri(),"your_db","mssql")
    #add to map
    QgsProject.instance().addMapLayer(vector_layer)
1
  • 1
    yep looks good.The only thing i would look at doing moving forward is making sure your 'tabelas' array is not hardcoded to those table names, but derived somehow from a predicate/query output. Otherwise your code will only ever work for those 5 tables.
    – nr_aus
    Aug 31 '20 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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