Create Spatialite database in QGis

Wednesday, July 6, 2011

Create Spatialite DB in QGis with Python is quite easy.

http://www.gaia-gis.it/spatialite-2.4.0-4/spatialite-cookbook/html/python.html has a very good tutorial.

Some remarks:
1. Initiality I use QGis 1.6 Standalone version, the spatilite version is 2.3.x. We need to add srid info into spatial_ref_sys manually.

2. Sample codes in QGis 1.6 plugin:
from pyspatialite import dbapi2 as sqlite3
dbName = str(self.txtOutputDB.text()) #textOutputDB is a lineEdit object(PyQt)

#if os.path.exists(dbName) :
ocon = sqlite3.connect(dbName)
ocur = ocon.cursor()

sql = 'SELECT InitSpatialMetadata()'
ocur.execute(sql)
#add projection information
sql = "INSERT INTO spatial_ref_sys (srid, auth_name, auth_srid, ref_sys_name, proj4text) VALUES (4326, 'epsg', 4326, 'WGS 84', '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs');"
ocur.execute(sql)


You can get the INSERT code from the following link:
http://www.gaia-gis.it/spatialite/init_spatialite-2.3.zip

3. After I switch to QGis 1.7, the spatialite version is updated, the projection info will be automatically created. However, an empty Spatialite database will have 3MB in size as there are many projection information in spatial_ref_sys table.

4. To reduce the size, I just keep several rows and delete unwanted srid in spatial_ref_sys table:

#delete unnecessary spatial_ref_sys
sql = 'DELETE FROM "spatial_ref_sys" where srid!= 2326 and srid!= 4326'
ocur.execute(sql)
sql = 'VACUUM'
ocur.execute(sql)