3

I'm having some troubles to create a new field in a postgis layer.This is the code I'm trying to use, but nothing happens, no field is created:

from PyQt4.QtCore import *

dbnam = "pruebapython"
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", dbnam, "postgres", "xxxxxxx")    
uri.setDataSource("", "masa", "geom","","gid")

layer = QgsVectorLayer(uri.uri(),"masa","postgres")
#layer = QgsVectorLayer('/xxx/xxx/xxxxx/xxx/xxx/DatosTest/MASA.SHP', 'MASA', "ogr")
layer.startEditing()

layer.dataProvider().addAttributes([QgsField("mytext", QVariant.LongLong )])
layer.updateFields()
layer.commitChanges()
idx = layer.fieldNameIndex( 'mytext' )
if idx == -1:
    print "No field"
else:
    QgsMapLayerRegistry.instance().addMapLayer(layer)
print 'Done!'

If I uncomment the layer which is a shapefile and I comment the posgres one, the field is created perfectly. What am I missing? Could anyone help me?

The QGIS log shows this:

Consulta errónea: ALTER TABLE "masa" ADD COLUMN "mytext"  devolvió 7 [ERROR:  syntax error at end of input
            LINE 1: ALTER TABLE "masa" ADD COLUMN "mytext"]

How can I solve this?

0
2

Not sure why you are getting that error, here is another option to add the column using psycopg2:

import psycopg2
conn = psycopg2.connect("dbname = 'dbName' port = '5432' user = 'postgres' host = 'serverName' password = '********'")
cur = conn.cursor()
sqlQuery = "ALTER TABLE tableName ADD COLUMN newColumnName numeric;"
cur.execute(sqlQuery)
conn.commit()
cur.close()
conn.close()

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