嗯,我有一个python程序来解析文件。这些文件中的数据如下所示:
Type=0x21
Label=2428
Data1=(54.67346,59.00001),(54.67415,59.00242),(54.67758,59.00001)
这是我的代码,它发送解析后的数据到MySql数据库
import MySQLdb
f = open('test.mp', 'r')
db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="gis", charset='utf8')
cursor = db.cursor()
i=0
for line in f.readlines():
if (line.startswith("Type")):
type=line[5:]
if (line.startswith("Label")):
label=line[6:]
if (line.startswith("Data")):
data=line[6:]
sql="""INSERT INTO `polylines` (Type, Label, Data) VALUES ('%(Type)s', '%(Label)s', '%(Data)s')"""%{"Type":type, "Label":label, "Data":data}
cursor.execute(sql)
db.commit()
db.close()
f.close()
我总是得到相同的错误-
_mysql_exceptions.OperationalError: (1416, 'Cannot get
geometry object from data you send to the GEOMETRY field')
我认为这是因为我将数据变量中的数据发送到数据库中的Linestring字段。我试图改变我发送的日期看起来像(1,1,2,2,3,3),但我又得到了这个错误。我应该如何更改数据并避免此错误?
嗯,经过一些研究和一些测试,我终于找到了答案。这个问题不是python,而是mysql。
首先,我们需要我们的Data变量看起来像Data="LineString(1 1,2 2,3 3)"
。然后,在插入函数中,我们应该写(GeomFromText('%(Data)s'))
,以帮助mysql从文本中获取几何形状。因此,整个Insert行看起来像这样:
sql="""INSERT INTO `polylines` (Type, Label, Data) VALUES ('%(Type)s', '%(Label)s', (GeomFromText('%(Data)s')))"""%{"Type":type, "Label":label, "Data":data}
现在它工作了!