psycopg语法错误对WKB字符串

时间:2016-04-06 19:35:35

标签: python gis psycopg2

我的代码执行一个简单的SQL查询,将一些WKB几何转换为WKT。我从url请求中获取了WKB几何。代码如下所示:

url = 'http://..........'
response = urllib2.urlopen(url).read()
responseJson = json.loads(response)
coordWKB = responseJson['wkb_geometry']
print(coordWKB)
cur.execute("SELECT ST_AsText(" + coordWKB + ")")

coordWKB看起来像这样:

'0106000020E6100000010000000103000000010000001200000017A84D0F39925EC083FC69A455C342400A1451BC48925EC0422CDC116B........'

但是我收到以下错误:

psycopg2.ProgrammingError: syntax error at or near "A84D0F39925EC083FC69A455C342400A1451BC48925EC0422CDC11................   
LINE 1: ...000020E6100000010000000103000000010000001200000017A84D0F3992...

如果我执行下面的代码,它可以工作:

cur.execute("select ST_AsText('0106000020E6100000010000000103000000010000001200000017A84D0F39925EC08.............')")

我似乎无法弄清楚我传递查询的WKB有什么问题。

1 个答案:

答案 0 :(得分:1)

首先阅读Understanding repr( ) function in Python。字符串coordWKB

'0106000020E6100000010000000103000000010000001200000017A84D0F39925EC083FC69A455C342400A1451BC48925EC0422CDC116B........'

不包含单引号,它只是python解释器为方便起见而显示字符串值的方式。如果确实包含单引号,那么它将显示为:

"'0106000020E6100000010000000103000000010000001200000017A84D0F39925EC083FC69A455C342400A1451BC48925EC0422CDC116B........'"

考虑到这一点

cur.execute("SELECT ST_AsText(" + coordWKB + ")")

生成的SQL将是:

SELECT ST_AsText(0106000020E6100000010000000103000000010000001200000017A84D0F39925EC083FC69A455C342400A1451BC48925EC0422CDC116B........)

显然这是错误的。

接下来,您应该阅读little Bobby Tables"the problem with the query parameters"的故事。您不应该通过连接字符串在SQL查询中包含值。这为SQL injection打开了大门。必须正确转义这些值,以便不会向查询中注入其他SQL。这是您的DB-API的工作,您所要做的就是用placeholders指示它。来自basic usage of psycopg2

# Pass data to fill a query placeholders and let Psycopg perform
# the correct conversion (no more SQL injections!)
>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
...      (100, "abc'def"))

请注意,您不要自己格式化查询字符串,而是将值元组作为参数传递给cur.execute。这样您的原始查询应该写为:

cur.execute("SELECT ST_AsText(%s)", (coordWKB,))