【发布时间】:2016-04-27 23:41:28
【问题描述】:
我在 python 中使用 MySQL 数据库。我有一个使用 MySQL 几何扩展的表,所以我需要在更新语句期间调用 GeomFromText MySQL 函数,如下所示:
UPDATE myTable SET Location=GeomFromText('Point(39.0 55.0)') where id=1;
UPDATE myTable SET Location=GeomFromText('Point(39.0 55.0)') where id=2;
最初,我使用的是低级 MySQLdb 库。我正在切换到使用 SQLAlchemy 核心库(出于速度和其他原因,我不能使用 SQLAlchemy ORM)。
如果我直接使用较低级别的 MySQLdb 库,我会这样做:
import MySQLdb as mysql
commandTemplate = "UPDATE myTable SET Location=GeomFromText(%s) where id=%s"
connection = mysql.connect(host="myhost",user="user",passwd="password",db="my_schema")
cursor = connection.cursor(mysql.cursors.DictCursor)
data = [
("Point(39.0 55.0)",1),
("Point(39.0 55.0)",2),
]
cursor.executemany(commandTemplate,data)
如何获得与 SQLAlchemy 核心相同的功能?
如果没有 GeomFromText,我认为它看起来像这样(感谢this answer):
from sqlalchemy.sql.expression import bindparam
updateCommand = myTable.update().where(id=bindparam("idToChange"))
data = [
{'idToChange':1,'Location':"Point(39.0 55.0)"},
{'idToChange':2,'Location':"Point(39.0 55.0)"},
]
connection.execute(updateCommand,data)
我不能直接将“Point(39.0 55.0)”替换为“GeomFromText('Point(39.0 55.0)')”,否则我会得到:
Cannot get geometry object from data you send to the GEOMETRY field
【问题讨论】:
标签: python mysql sqlalchemy