7

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
Vince
  • 20,017
  • 15
  • 45
  • 64
jessie jes
  • 1,061
  • 8
  • 21
  • 1
    Does your SQL find something when you run it with ogrinfo? – user30184 Apr 26 '17 at 20:24
  • no I need like this in editor with python but I sure to have value – jessie jes Apr 26 '17 at 20:30
  • I meant that do you know that the SQL part is OK? Test with 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. – user30184 Apr 26 '17 at 20:35
  • 1
    yes I get it I take correct result now how to do in python ? – jessie jes Apr 26 '17 at 20:36
  • I guess that you have only opened the GDAL datasource but not the layer and you should get first a layer to query with something like layer = dataSource.GetLayer(). Taken from an example https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html#get-shapefile-feature-count. – user30184 Apr 26 '17 at 20:45
  • It was not meant for copy-paste but to make you think. I do not use python myself, sorry. – user30184 Apr 26 '17 at 21:18
  • from osgeo import ogr import os

    shapefile = "line.shp" driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(shapefile, 0) layer1 = dataSource.GetLayer() TEST=3

    sql = "SELECT id FROM {} where id={}".format(shapefile,TEST) print sql layer = shapefile.ExecuteSQL(sql) print layer

    – jessie jes Apr 26 '17 at 21:19

1 Answers1

4

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.

mgri
  • 16,159
  • 6
  • 47
  • 80