How to create a SpatiaLite Layer in QGIS 3 with Python?

Just opened a PR to fix this issue in QGIS v3 (on Windows). Remember that this is a dev version.

In the meantime, you could use this installer and adjust it by yourself (free software rocks!) after installation. You just need to change line 602 of C:\\Program Files\\QGIS 2.99\\apps\\qgis-dev\\python\\qgis\\utils.py by:

    ("spatialite", "spatialite_init_ex"),

Restart QGIS and now you'll be able to use sqlite3 connections with SpatiaLite support by using the following line from the QGIS Python Console or from your plugin:

con = qgis.utils.spatialite_connect("/path/to/your/spatialite_db.sqlite")

Now, you can create a new point layer in your database in this way (see the docs):

cur = con.cursor()
# Run next line if your DB was just created, it may take a while...
cur.execute("SELECT InitSpatialMetaData()") 
cur.execute("""CREATE TABLE test_geom (
  id INTEGER NOT NULL
    PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  measured_value DOUBLE NOT NULL);""")
cur.execute("""SELECT AddGeometryColumn('test_geom', 'the_geom',
  4326, 'POINT', 'XY');""")
cur.close()
con.close()

This little fix also makes db_manager able to open SpatiaLite databases.


As Jürgen Fischer said on the bug tracker feed here

Use sqlite3 instead of pyspatialite for SpatiaLite connections

  • get the utils.py file revision https://issues.qgis.org/projects/qgis/repository/revisions/6402160526e3176d1d41f422d6ecab59aa7ac68d
  • thank the editor gcarrillo