3

I have a code to open the layers of a SQLite database. When executing this code, the layers are loaded correctly (1 & 2). However i also need to connect to the database and show the connection in the browser toolbar.

How doe load the connection and let it show in the database browser (3)?

uri = QgsDataSourceUri()
uri.setDatabase(r'C:\\path_to_db\\andorra.sqlite')
schema = ''
tables = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other_relations']
display_names = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other relations']
geom_column = 'geometry'

for i in range(len(tables)):
     uri.setDataSource(schema, tables[i], geom_column)
     iface.addVectorLayer(uri.uri(), display_names[i], 'spatialite')

Screenshot

2 Answers 2

4

I have found an answer:

con = ['name_of_db','C:\\path_to_db\\andorra.sqlite']
QSettings().setValue("SpatiaLite/connections/%s/sqlitepath" %(con[0]), con[1])
iface.reloadConnections()

This code will create an 'visible' connection with the given sqlite database.

Complete code:

    conn = sqlite3.connect(r'C:\\path_to_db\\andorra.sqlite')
    uri = QgsDataSourceUri()
    uri.setDatabase(r'C:\\\\path_to_db\\andorra.sqlite')
    schema = ''
    tables = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other_relations']
    display_names = ['points', 'lines', 'multilinestrings', 'multipolygons', 'other relations']
    geom_column = 'geometry'

    for i in range(len(tables)):
        uri.setDataSource(schema, tables[i], geom_column)
        iface.addVectorLayer(uri.uri(), display_names[i], 'spatialite')

    db = ['andorra','\\path_to_db\\andorra.sqlite']
    QSettings().setValue("SpatiaLite/connections/%s/sqlitepath" %(db[0]), db[1])
    iface.reloadConnections()

    set_crs = QgsCoordinateReferenceSystem(3857)
    QgsProject.instance().setCrs(set_crs)  #setting the osm CRS
1
  • Hi I'm currently trying to do the same thing for a geopackage. Any idea how I should adapt this line: QSettings().setValue("SpatiaLite/connections/%s/sqlitepath" %(con[0]), con[1]) - i've already tried QSettings().setValue("GeoPackage/connections/%s/geopackagepath" %(con[0]), con[1]) but that doesn't seem to do it...
    – lhowarth
    Feb 11, 2021 at 12:56
0

For GeoPackage, try:

QSettings().setValue("providers/ogr/GPKG/connections/%s/path" %(con[0]),con[1])

Your Answer

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

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