[GIS] Export vector layer to sqlite database using PyQGIS

pyqgisspatialite

I have successfully created a (virtual) polygon layer named vlyr. I also have a QgsFeature object called poly. I also added two fields to my layer called "name" and "size".

Now I want to export my polygons to a sqlite database which I manually created for testing purposes. It is called test.sqlite.

I am able to establish a db connection and create a new sqlite table using the following code

import sqlite3 as lite 
import sys 

con = lite.connect('test.sqlite')
for l in vlyr.getFeatures(): 

    with con: 
        cur = con.cursor() 
        abc = (
              (1, 'fstName', 6543.12), 
              (2, 'sndName', 12635.11)
            )
        cur.execute("DROP TABLE IF EXISTS Polygonx")
        cur.execute("CREATE TABLE Polygonx (Id PRIMARY KEY, Name TEXT, Size REAL)")
        cur.executemany("INSERT INTO Polygonx VALUES (?,?,?)", abc)
        cur.execute("SELECT * FROM Polygonx")
        rows = cur.fetchall()
        for row in rows:
            print row

I also stored the geometry in a variable called a, but am currently not doing much with it:

a = (l.geometry().exportToWkt())

My question is: how can I create abc dynamically, that is, from my existing polygon layer and add the geometry?

Best Answer

Another option would be to use the QgsVectorFileWriter to save a memory layer to sqlite/spatiallite db:

QgsVectorFileWriter.writeAsVectorFormat(vlyr, newSQLiteFilePath,"utf-8", crs, "SQLite", False, None ,["SPATIALITE=YES"])
Related Question