2

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?

3

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"])
2

Hooray, I was able to fill the field dynamically by changing my code the following way:

feature_list = []
    for feature in vlyr.getFeatures():
        attributes = feature.attributes()
        new_feature = (feature.id(), attributes[0], attributes[1])
        feature_list.append(new_feature)
    with con: 
        cur = con.cursor()
        cur.execute("CREATE TABLE Polygonx (Id PRIMARY KEY, Name TEXT, Size REAL)")
        cur.executemany("INSERT INTO Polygonx VALUES (?,?,?)", feature_list)
        cur.execute("SELECT InitSpatialMetadata()") 
        cur.execute("SELECT AddGeometryColumn('Polygonx', 'geometry', 4326, 'POLYGON', 'XY')")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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