无法使用executemany执行ST_GEOMFROMTEXT

时间:2017-06-13 18:50:05

标签: python mysql python-3.x mysql-connector

在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函数,我非常有信心这是将空间数据添加到几何字段的正确方法(字段&#39; location&#39;有类型&# 39; POINT&#39)。如上所示,它不需要在它周围使用引号来在命令行工作(这通常是我经验中的关键点)。

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

1 个答案:

答案 0 :(得分: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 +"') )"