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
1 Answer 1
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
<osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x18A4D8F0> >
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.
-
show me
driver
not definejessie jes– jessie jes2017年04月26日 21:31:56 +00:00Commented Apr 26, 2017 at 21:31 -
@jessiejes Sorry, there was a missing line. I edited the answer.mgri– mgri2017年04月26日 21:33:53 +00:00Commented Apr 26, 2017 at 21:33
-
now I take this
<osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x03166D88> >
but I need the id for example if select id is 6 then I need to take only this value 6 in the print layerjessie jes– jessie jes2017年04月26日 21:37:33 +00:00Commented Apr 26, 2017 at 21:37
ogrinfo -sql "SELECT id FROM line where id=3" line.shp
. If you get "3" it is OK and the issue can only be in your Python code.