Python – How to Connect to SpatiaLite Database Using OGR

gdalogrpostgresqlpythonsqlite

I need to connect to a SQLite/SpatiaLite database to copy data there. I have done the same with PostgreSQL/PostGIS like this:

connection_string = "dbname={} user={} password={} host={} port={}".format(
                self.dbname,
                config.get_config_value(dbsettings, "user"),
                config.get_config_value(dbsettings, "password"),
                config.get_config_value(dbsettings, "host"),
                config.get_config_value(dbsettings, "port")
            )
ogr.Open("PG:" + connection_string)

I followed instructions here where it is specified how to connect to PostgreSQL. But in the SQLite section, there isn't any information on connecting to the database. I suppose there also will be a connection string with a path to the database file instead of port and host but I need the exact syntax.

I am using Python 3.5.

EDIT:

I need to use ogr.open (not sqlite3.connect) because I store data to the database using CopyLayer (a method of ogr.open) as can be seen here (this is for PsotgreSQL):

    dsc_in = ogr.Open(file_name)
    dsc_out = ogr.Open("PG:" + self.target)

    layer = dsc_out.CopyLayer(dsc_in.GetLayer(), identifier,
                              ['OVERWRITE=YES'])
    if layer is None:
        raise Exception("Writing output data to the database failed.")

Best Answer

As far as I know, I don't think you need to build a connection string (as opposed to db services) for sqlite connections. This works fine for me:

from osgeo import ogr
ds = ogr.Open('spatialite.db')

for i in range(ds.GetLayerCount()):
    print(df.GetLayerByIndex(i).GetName())
Related Question