[gdal-dev] Updating a single PostgreSQL field from ogr/python

Martin Jensen martin.martinjensen at gmail.com
Sat May 12 13:43:23 EDT 2012


Hi list,

I was trying to do the following with ogr python bindings

   1. Create  srclayer from PostGIS based on sql statement
   2. Copy srclayer to dstlayer (also PostGIS)
   3. Add new field to dstlayer
   4. assign value to new field

My code is this:

### Open Database

Driver = ogr.GetDriverByName('PostgreSQL')

db = 'pg:host=localhost dbname=test user=postgres password=secret'

dataSource = Driver.Open(db,1 )

## crate source and destination layer

srclayer = dataSource.ExecuteSQL("SELECT gid,aar,ejd_areal,pris, geom FROM
salg WHERE aar=2010 AND pris >0 AND ejd_areal >0 limit 15")

dstlayer = dataSource.CopyLayer(srclayer,'gwr.dstlayer', options = [
'OVERWRITE=YES'] )

## add field to copied layer

fieldDefn = ogr.FieldDefn('gradient', ogr.OFTReal)

dstlayer.CreateField(fieldDefn)

#outFeature = ogr.Feature(dstlayer.GetLayerDefn())

outFeature = dstlayer.GetNextFeature()

## update the new field

for feature in dstlayer:

    outFeature.SetField('gradient',666) ##set this field only

    outFeature.SetFID(-1) ## tried to unset ogc_fid so not violating pk
column constraint

    dstlayer.CreateFeature(outFeature)

    outFeature = dstlayer.GetNextFeature()


I get the error:

ERROR:  duplicate key value violates unique constraint "dstlayer_pk"
DETAIL:  Key (ogc_fid)=(1) already exists.


I have a feeling i'm missing something really simple here.

Any suggestions would be much appreciated!

Software:
GDAL 1.9
PG: PostgreSQL version string : 'PostgreSQL 9.1.3 on
x86_64-apple-darwin11.3.0, compiled by i686-apple-darwin11-llvm-gcc-4.2
(GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00), 64-bit'
PG: PostGIS version string : '2.0 USE_GEOS=1 USE_PROJ=1 USE_STATS=1'

Best regards

Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/gdal-dev/attachments/20120512/de5bd90c/attachment.html


More information about the gdal-dev mailing list