无法使用executemany执行ST_GEOMFROMTEXT

问题描述 投票:0回答:2

在Ubuntu 16.04上使用python 3.5和mysql 5.7.18,我无法在executemany语句中使用ST_GEOMFROMTEXT函数。

使用此代码:

    print(query)
    print(add_vals[-1:])        
    zip_cursor.executemany(query, add_vals[-1:])

我得到以下输出:

INSERT INTO zipcodes (zipcode, name, area, pop, emp, emp_pay, households, location) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);
[["'54517'", "'CLAM LAKE, WI'", 201.441702, 112, 10, 600, 59, "ST_GEOMFROMTEXT('POINT(46.145917 -90.930676)')"]]
Traceback (most recent call last):
  File "zip_parse.py", line 319, in <module>
    main()
  File "zip_parse.py", line 32, in main
    insert_data(zip_db, zip_cursor, data)
  File "zip_parse.py", line 160, in insert_data
    zip_cursor.executemany(query, add_vals[-1:])
  File "/usr/local/lib/python3.5/dist-packages/mysql/connector/cursor.py", line 618, in executemany
    return self.execute(stmt)
  File "/usr/local/lib/python3.5/dist-packages/mysql/connector/cursor.py", line 515, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/local/lib/python3.5/dist-packages/mysql/connector/connection.py", line 488, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/local/lib/python3.5/dist-packages/mysql/connector/connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.DataError: 1416 (22003): Cannot get geometry object from data you send to the GEOMETRY field

但是,当复制到 mysql 命令行时,传递的语句似乎运行得很好:

mysql> INSERT INTO zipcodes (zipcode, name, area, pop, emp, emp_pay, households, location) VALUES ('54517','CLAM LAKE, WI',201.441702,112,10,600,59,ST_GEOMFROMTEXT('POINT(46.145917 -90.930676)'));
Query OK, 1 row affected (0.05 sec)

我过去广泛使用过 ST_GEOMFROMTEXT 函数,并且我非常有信心这是将空间数据添加到几何字段(字段“location”的类型为“POINT”)的正确方法。正如所演示的,它不需要引号就可以在命令行中工作(这通常是我经验中的症结所在)。

关于为什么这不适用于执行很多的任何想法?

python mysql python-3.x mysql-connector
2个回答
1
投票

我也有同样的问题:

import pymysql

point = 'POINT(18.16 -66.72)'
geojson = '{ "type": "Point", "coordinates": [102.0, 0.0]}'

以下代码片段不起作用:

"INSERT INTO `zip`(`id`, `zip`, `location`, `geometry`) VALUES (NULL,100, ST_PointFromText('%s'), ST_GeomFromGeoJSON('%s') )"
qparams = (point, geojson)
cursor.execute(sql, qparams)

所以答案是这样使用它:

"INSERT INTO `zip`(`id`, `zip`, `location`, `geometry`) VALUES (NULL,100, ST_PointFromText('"+ point +"'), ST_GeomFromGeoJSON('"+ geojson +"') )"

0
投票

您必须将 ST_GEOMFROMTEXT 放入 sql 模板中,而不是放在值数组中。就像这样,而不是这个:

query = "INSERT INTO zipcodes (zipcode, name, area, pop, emp, emp_pay, households, location) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"

你需要这个:

query = "INSERT INTO zipcodes (zipcode, name, area, pop, emp, emp_pay, households, location) VALUES (%s,%s,%s,%s,%s,%s,%s,ST_GEOMFROMTEXT(%s)"

然后在您的 add_vals 列表中,代替“location”的字符串:

"ST_GEOMFROMTEXT('POINT(46.145917 -90.930676)')"

你需要这个字符串:

"POINT(46.145917 -90.930676)"

将 SRID 作为第二个参数添加到 ST_GEOMFROMTEXT 也是一个好主意。

© www.soinside.com 2019 - 2024. All rights reserved.