1

I am using the QGIS python console to load a SQL Server layer in QGIS using the follow code:

uri = "MSSQL:{MYSERVER};database={MYDATABASE};tables= MYTABLE};trusted_connection=yes"
lpBatch = QgsVectorLayer(uri_lp, "PREM_LP_Batch", "ogr")
QgsProject.instance().addMapLayer(lpBatch)

It loads fine, and I can browse the layer fine. However, upon attempting to save any changes made to the geometries, I get the following error:

Layer PREM_INT_Batch: OGR error setting feature 170: Error updating feature with FID:170, [22001][Microsoft][SQL Server Native Client 11.0]String data, right truncation(0)

I have found the data types/lengths of the attributes are incorrect. I believe this is leading to the truncation error, as it thinks the values of the fields are too long.

If I load the layer using the UI, the data types/lengths of the attributes are as they should be, and I can save any changes I make to the geometries fine.

Any idea how I can load the attributes correctly through the python console?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jan 14, 2020 at 9:50

1 Answer 1

1

I have found a solution. Loading the layer using QgsDataSourceUri loads the layer using the correct attribute table, and allows editing and saving of geometries:

uri = QgsDataSourceUri()
uri.setConnection({HOST},{PORT}, {DB}, {UID}, {PWD})
uri.setUseEstimatedMetadata(1)
uri.setSrid("27700")
uri.setWkbType(QgsWkbTypes.Polygon)
uri.setDataSource({SCHEMA},{TABLE},{GEOMETRY COLUMN})
intFull = QgsVectorLayer(uri.uri(), "Azure_INT_FULL", "mssql")
QgsProject.instance().addMapLayer(intFull)
answered Jan 14, 2020 at 13:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.