Sunday 27 December 2015

SQL queries in shapefiles using python/gdal return none result



I want try use Python and GDAL to create some SQL queries in my shapefiles. I try something and it looks good, but doesn't work. I get a none result.


Here is the code :


from osgeo import ogr
ogr_ds = ogr.Open('line.shp')
TEST=3
sql = "SELECT id FROM {} where id='{}'".format(ogr_ds,TEST)
layer = ogr_ds.ExecuteSQL(sql)
print layer

Answer



You are probably using the input layer in a wrong way; furthermore, also the .format{} operation doesn't seem correct.



You may try the following code:


from osgeo import ogr

filepath = 'C:/Users/path_to_the_shapefile/line.shp' # set the filepath
layer_name = filepath[:-4].split('/')[-1] # get the layer name
driver = ogr.GetDriverByName ("ESRI Shapefile")
ogr_ds = driver.Open(filepath)
TEST=3
sql = "SELECT id FROM %s WHERE id=%s" %(layer_name,TEST)
layer = ogr_ds.ExecuteSQL(sql)

print layer

I tested it with another shapefile (and a similar query) and it returns what expected:


print layer
>

EDIT


If you want to print the id value, you may add these lines:


feat = layer.GetNextFeature()
val = feat.GetField(0)

print val

but this will only returns one feature and not all the queried features (this kind of operation would be useful if you are only interested in knowing if a specific value for the id field is stored in the input layer). Furthermore, you will get an error if there isn't any id value equals to the TEST variable.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...