问题描述
我在设计一个使用 psycopg2 库规范的好算法时遇到了一些问题 这里
i have some problem to design a good algorithm which use specification of psycopg2 library described here
我想建立一个与这个字符串相等的动态查询:
i want to build a dynamic query equal to this string :
select st_geomfromtext('polygon((0.0 0.0,20.0 0.0,20.0 20.0,0.0 20.0,0.0 0.0))');
如您所见,我的 polygon 对象包含多个点,读取一个简单的 csv 文件 some.csv,其中包含:
as you can see, my polygon object contain multiple point, read in a simple csv file some.csv which contain :
0.0;0.0 20.0;0.0 20.0;20.0 0.0;20.0 0.0;0.0
所以我动态构建查询,csv 中行/数据数的函数.
so i build the query dynamically, function of the number of line/data in the csv.
这里我的程序生成要执行的 sql query 字符串:
here my program to generate the sql query string to execute :
import psycopg2 import csv # list of points lxy = [] dsn= "dbname='tests' user='postgres' password='postgres' host='localhost'" conn = psycopg2.connect(dsn) curs = conn.cursor() def genpointtext(curs,x,y): generatedpoint = "%s %s" % (x,y) return generatedpoint #lecture fichier csv polygonfile = open('some.csv', 'rb') readercsv = csv.reader(polygonfile,delimiter = ';') for coordinates in readercsv: lxy.append(genpointtext(curs,float(coordinates[0]),float(coordinates[1]))) # function of list concatenation by separator def convert(mylist,separator): return separator.join([str(i) for i in mylist]) # construct simple query with psycopg def genpolygontext(curs,l): # http://initd.org/psycopg/docs/usage.html#python-types-adaptation generatedpolygon = "polygon((%s))" % convert(l, ",") return generatedpolygon def executewkt(curs,geomobject,srid): try: # geometry st_geomfromtext(text wkt, integer srid); finalwkt = "select st_geomfromtext('%s');" % (geomobject) print finalwkt curs.execute(finalwkt) except psycopg2.programmingerror,err: print "error = " , err polygonquery = genpolygontext(curs,lxy) executewkt(curs,polygonquery,4326)
如您所见,这是可行的,但是由于python对象和sql postgresql对象之间的转换问题,这种方式不正确.
as you can see, that's works, but this way is not correct because of conversion problem between python object and sql postgresql object.
在文档中,我只看到了为静态查询提供和转换数据的示例.您是否知道在查询的动态构建中创建具有正确类型的正确字符串的优雅"方式?
in the documentation, i see only example to feed and convert data for static query. do you know an "elegant" way to create correct string with correct type in a dynamic build for query ?
更新 1:
如你所见,当我在这个简单的例子中使用 psycopg 类型转换函数时,我有这样的错误:
as you can see, when i use psycopg type transformation function on this simple example, i have error like this :
<代码>查询= st_geomfromtext( 'polygon((52.146542 19.050557,52.148430 19.045527,52.149525 19.045831,52.147400 19.050780,52.147400 19.050780,52.146542 19.050557))',4326)"名称 = 我的表"尝试:curs.execute('insert into %s(name, url, id, point_geom, poly_geom) values (%s);', (name,query))除了 psycopg2.programmingerror,错误:打印错误=",错误
错误相等:
error = erreur: erreur de syntaxe sur ou près de ? e'my_table' ? line 1: insert into e'my_table'(name, poly_geom) values (e'st_geomfr...
更新 2:
感谢stackoverflow用户的最终代码!
final code which work thanks to stackoverflow users !
#info lib : http://www.initd.org/psycopg/docs/ import psycopg2 # info lib : http://www.51sjk.com/upload/articles/1/0/340/340412_20221223101847450.html import csv # list of points lxy = [] dsn= "dbname='tests' user='postgres' password='postgres' host='localhost'" print "opening connection using dns:", dsn conn = psycopg2.connect(dsn) curs = conn.cursor() def genpointtext(curs,x,y): generatedpoint = "%s %s" % (x,y) return generatedpoint #lecture fichier csv polygonfile = open('some.csv', 'rb') readercsv = csv.reader(polygonfile,delimiter = ';') for coordinates in readercsv: lxy.append(genpointtext(curs,float(coordinates[0]),float(coordinates[1]))) # function of list concatenation by separator def convert(mylist,separator): return separator.join([str(i) for i in mylist]) # construct simple query with psycopg def genpolygontext(l): # http://initd.org/psycopg/docs/usage.html#python-types-adaptation generatedpolygon = "polygon((%s))" % convert(l, ",") return generatedpolygon def generateinsert(curs,tablename,name,geomobject): curs.execute('insert into binome1(name,geom) values (%s, %s);' , (name,geomobject)) def create_db_binome(conn,name): curs = conn.cursor() sql = ( "create table %s" " (" " polyname character varying(15)," " geom geometry," " id serial not null," " constraint id_key primary key (id)" " )" " with (" " oids=false" " );" " alter table %s owner to postgres;" ) %(name,name) try: #print sql curs.execute(sql) except psycopg2.programmingerror,err: conn.rollback() dropquery = "alter table %s drop constraint id_key; drop table %s;" % (name,name) curs.execute(dropquery) curs.execute(sql) conn.commit() def insert_geometry(polyname,tablename,geometry): escaped_name = tablename.replace('""','""') try: test = 'insert into %s(polyname, geom) values(%%s, st_geomfromtext(%%s,%%s))' % (escaped_name) curs.execute(test, (tablename, geometry, 4326)) conn.commit() except psycopg2.programmingerror,err: print "error = " , err ################ # program main # ################ polygonquery = genpolygontext(lxy) srid = 4326 table = "binome1" create_db_binome(conn,table) insert_geometry("berlin",table,polygonquery) insert_geometry("paris",table,polygonquery) polygonfile.close() conn.close()
推荐答案
您正在尝试将表名作为参数传递.如果您只是查看 postgresql 错误日志,您可能会立即看到这一点.
you are trying to pass a table name as a parameter. you probably could've seen this immediately if you'd just looked at the postgresql error log.
您试图通过 psycopg2 作为参数传递的表名被转义,产生如下查询:
the table name you're trying to pass through psycopg2 as a parameter is being escaped, producing a query like:
insert into e'my_table'(name, url, id, point_geom, poly_geom) values (e'st_geomfromtext(''polygon(( 52.146542 19.050557, 52.148430 19.045527, 52.149525 19.045831, 52.147400 19.050780, 52.147400 19.050780, 52.146542 19.050557))'',4326)');'
这不是您想要的,也不会起作用;你不能像文字一样转义表名.必须使用普通的 python 字符串插值来构造动态 sql,对于实际字面值,只能使用参数化语句占位符.
this isn't what you intended and won't work; you can't escape a table name like a literal. you must use normal python string interpolation to construct dynamic sql, you can only use parameterized statement placeholders for actual literal values.
params = ('polygon(( 52.146542 19.050557, 52.148430 19.045527, 52.149525 19.045831, 52.147400 19.050780, 52.147400 19.050780, 52.146542 19.050557))',4326) escaped_name = name.replace('"",'""') curs.execute('insert into "%s"(name, url, id, point_geom, poly_geom) values (st_geomfromtext(%%s,%%s));' % escaped_name, params)
看看我是如何直接插入名称来生成查询字符串的:
see how i've interpolated the name directly to produce the query string:
insert into my_table(name, url, id, point_geom, poly_geom) values (st_geomfromtext(%s,%s));
(%% 通过 % 替换转换为纯 %).然后我将该查询与定义 polygon 的字符串和 st_geomfromtext 的另一个参数作为查询参数一起使用.
(%% gets converted to plain % by % substitution). then i'm using that query with the string defining the polygon and the other argument to st_geomfromtext as query parameters.
我没有对此进行测试,但它应该可以为您提供正确的想法并帮助您解释问题所在.
i haven't tested this, but it should give you the right idea and help explain what's wrong.
非常小心在进行这样的字符串插值时,这是 的简单途径sql 注入.我在上面显示的代码中做了非常粗略的引用,但是如果您的客户端库提供了一个正确的标识符引用函数,我想使用它.
be extemely careful when doing string interpolation like this, it's an easy avenue for sql injection. i've done very crude quoting in the code shown above, but i'd want to use a proper identifier quoting function if your client library offers one.