2

I am trying to add data into Postgis via gdal/ogr in python. However, if I first use OGRDataSource.CreateLayer("test") to create layer, then I can add new feature sucessfully. However, when tables are already defined in the database, if I use OGRDataSource.GetLayer(table_name) to get the layer and then try to add/edit feature. It does not work.

I do found differences after running OGRLayer.TestCapabilities() on both layers. If layer is reference by CreateLayer(), the capabilities such as SequentialWrite and RandomWrite are both True. If the layer is reference to existed tables using GetLayer(), at least those two capabilities are False. Which I think explained the reason why add feature fails. But how can I enable them or what is the better way to insert new record(no geometry) into Postgis in Python?

**# The user is the owner of this database**.
conn_str = "PG: host=%s dbname=%s user=%s password=%s" %('localhost', 'CEdB', 'test', 'test')
conn = ogr.Open(conn_str)

def this_create_layer_and_add_feature_OK():
    # here we create test_made table
    layer = conn.CreateLayer('test_made', None, ogr.wkbUnknown, ['OVERWRITE=YES'])
    # add new fields
    err_code = layer.CreateField(ogr.FieldDefn('object_id', ogr.OFTInteger))
    field_def = ogr.FieldDefn('name', ogr.OFTString)
    field_def.SetWidth(50)
    err_code = layer.CreateField(field_def)
    feature = ogr.Feature(layer.GetLayerDefn())
    feature.SetField('object_id', 1)
    feature.SetField('name', 'testing')
    layer.StartTransaction()
    err_code = layer.CreateFeature(feature)
    feature = None
    layer.CommitTransaction()


def this_not_create_feature_in_table():
    # test_table is a predefined table, with 2 columns, no geometry!
    lyr = conn.GetLayer("test")
    new_feature = ogr.Feature(lyr.GetLayerDefn())
    new_feature.SetField("object_id", 1)
    new_feature.SetField("name", 'testing')
    lyr.StartTransaction()
    if lyr.CreateFeature(new_feature) == ogr.OGRERR_NONE:
        new_feature = None
        err_code = lyr.CommitTransaction()

Your Answer

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

Browse other questions tagged or ask your own question.