用Python INSERT INTO和字符串连接

| 在将数据插入到数据库中时,我遇到了重大的减速。您可以从下面的代码中看到,我只是在构建SQL语句以传递给execute命令。值是正确的,并且一切都很好,但是python解释器似乎在运行时从参数中添加和删除了引号。 这是将空间数据插入数据库的正确方法。
INSERT INTO my_table(
            name, url, id, point_geom, poly_geom)
    VALUES (\'test\', \'http://myurl\', \'26971012\', 
            ST_GeomFromText(\'POINT(52.147400 19.050780)\',4326), 
            ST_GeomFromText(\'POLYGON(( 52.146542 19.050557, bleh, bleh, bleh))\',4326));
这可以在Postgres查询编辑器中验证...现在,当我运行下面的Python代码时,它将在ST_GeomFromText函数周围添加双引号,然后从id列中删除引号。
INSERT INTO my_table(
            name, url, id, point_geom, poly_geom)
    VALUES (\'test\', \'http://myurl\', 26971012, 
     \"ST_GeomFromText(\'POINT(52.147400 19.050780)\',4326)\", 
     \"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)\");
这会导致插入失败,PostGIS声称这不是正确的几何图形。当我在屏幕上打印要查看的每个参数时,引号并没有发生什么有趣的事情,因此我认为问题必须出在execute命令中。我正在使用Python 2.7 ...有人可以伸出援手来防止这种疯狂持续吗?
    conn = psycopg2.connect(\'dbname=mydb user=postgres password=password\')
    cur = conn.cursor()
    SQL = \'INSERT INTO my_table (name, url, id, point_geom, poly_geom) VALUES (%s,%s,%s,%s,%s);\'
    Data = name, url, id, point, polygon
    #print Data
    cur.execute(SQL, Data)
    conn.commit()
    cur.close()
    conn.close()
    
已邀请:
您将字符串“ 3”作为参数传递,而psycopg2对其进行了转义。但是,“ 4”是PostGIS函数,而不是您要插入的数据。 要解决此问题,您需要将
ST_GeomFromText
函数移到静态SQL中。例如:
sql = \'\'\'
   INSERT INTO foo (point_geom, poly_geom)
   VALUES (ST_PointFromText(%s, 4326), ST_GeomFromText(%s, 4326))\'\'\'
params = [\'POINT( 20 20 )\', \'POLYGON(( 0 0, 0 10, 10 10, 10 0, 0 0 ))\']
cur.execute(sql, params)
    
做这样的事情更好(编辑:比你在做什么,而不是第一个答案):
select st_asgeojson(the_geom_ls) from atlas where the_geom_ls &&\\
st_geomfromtext(\'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))\', 4326)
并将其与元组中的坐标一起传递给适配器,它们将被正确解析。到目前为止,这是最简单的方法。如果确实需要分别构造字符串,则可以通过查看
cur.mogrify
的输出来清理转义:
cur.mogrify(\'INSERT INTO my_table (name, url, id, point_geom, poly_geom) VALUES (%s,%s,%s,%s,%s);\', (1,2,3,4,5))
>>>\'INSERT INTO my_table (name, url, id, point_geom, poly_geom) VALUES (1,2,3,4,5);\'

query = \"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)\"

cur.mogrify(\'INSERT INTO my_table (name, url, id, point_geom, poly_geom) VALUES (%s,%s,%s,%s,%s);\', (1,2,3,4,query))
>>> \"INSERT INTO my_table (name, url, id, point_geom, poly_geom) VALUES (1,2,3,4,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)\');\"
抵制在sql查询字符串上使用字符串格式化方法的诱惑,即使这些事情可能令人沮丧。     

要回复问题请先登录注册