[Qgis-user] Saving values by a Python-Script in a PostgreSQL-Database

Kai Behncke Kai.Behncke at ibbenbueren.de
Mon May 27 00:54:43 PDT 2019


Dear users,

I try to save attributes in PostgreSQL/PostGIS
by a Python Script.

So far I get a connection and I can set an additional attribute field
that I can fill with a value (it seems so).
But how can I save these values?


My script looks like:

from qgis.core import
QgsApplication,QgsVectorLayer,QgsVectorDataProvider,QgsDataSourceUri
from PyQt5.QtCore import *
from qgis.PyQt.QtSql import QSqlDatabase, QSqlQuery

uri2 = QgsDataSourceUri()
uri2.setConnection("server", "5432", "table", "user", "pw")
		    #set database schema, table name, geometry column
and optionaly subset(WHERE clause)
uri2.setDataSource ("public", "table", "geom")
		    # Defining the layer name and layer type for QGIS?
vlayer2=QgsVectorLayer (uri2.uri() ,"ww_manhole","postgres")
print (vlayer2.isValid())
if (vlayer2.startEditing()):
    print ("ok startEditing")
else:
    print("not ok")
 
my_field_name2 = 'new_field'
if (vlayer2.addAttribute(QgsField(my_field_name2, QVariant.String))):
    print ("ok AddAttribute")
else:
    print ("not ok2")

my_field_value2 = 'Hello world!'
for f in vlayer2.getFeatures():
    print ("ok getFeature")
    f[my_field_name2] = my_field_value2
    if (vlayer2.updateFeature(f)):
	    print ("ok updatefeature")
    else:
	    print ("not ok updatefeature")

if (vlayer2.updateFields()):
	    print ("ok updateFields") 
   else:
	    print ("not ok updateFields")
if (vlayer2.commitChanges()):
    print ("ok commitChanges")
else:
    print("not ok commitChanges")



The output shows that neither
updateFields works not commitChanges??
Could anybode help please?

Thank you very much, Kai

The output:

True
ok startEditing
ok AddAttribute
ok getFeature
ok updatefeature
not ok updateFields
not ok commitChanges

Mit freundlichen Grüßen
Im Auftrag

Kai Behncke
Geoinformation
Tel.: +49 5451 931-7125

E-Mail: kai.behncke at ibbenbueren.de 

Rathaus II
Roncallistraße 3-5
1. Stock, Raum 105
49477 Ibbenbüren



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20190527/91c82293/attachment.html>


More information about the Qgis-user mailing list