TransWikia.com

How QGIS Python loop through all tables MS SQL Server?

Geographic Information Systems Asked by Flavio Felix on August 5, 2021

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.xxxxx", "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

2 Answers

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)

Answered by Flavio Felix on August 5, 2021

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 

Answered by Santfloyd on August 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP