英文:
How to insert POINT into mysql using gorm?
问题
func (loc Location) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "POINT(?)",
Vars: []interface{}{fmt.Sprintf("%f, %f", loc.X, loc.Y)},
}
}
这是我的值转换函数。它创建了一个查询语句,类似于 POINT('XX.XXXXX, YY.YYYYY')
。但是由于单引号的问题,这个查询语句无法正常工作。你可以如何解决这个问题?
英文:
func (loc Location) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "POINT(?)",
Vars: []interface{}{fmt.Sprintf("%f, %f", loc.X, loc.Y)},
}
}
This is my valuer. And it creates a query like this POINT('XX.XXXXX, YY.YYYYY')
. But this query does not work because of single quotation marks. How can I solve this problem?
答案1
得分: 0
一种解决方法可能是使用MySQL特定的函数,如GeomFromText
或PointFromText
,将字符串转换为空间数据类型。
func (loc Location) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "PointFromText(?)",
Vars: []interface{}{fmt.Sprintf("POINT(%f %f)", loc.X, loc.Y)},
}
}
更多详细信息请参考这里。另外,请注意根据您使用的MySQL版本,这些函数的名称可能不同。例如,MySQL 5.6的PointFromText
函数对应于MySQL 8.0的ST_PointFromText
函数。
英文:
One solution might be to use MySQL-specific functions like GeomFromText
or PointFromText
to convert the string to spatial data type.
func (loc Location) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "PointFromText(?)",
Vars: []interface{}{fmt.Sprintf("POINT(%f %f)", loc.X, loc.Y)},
}
}
More details are provided here. Also, please note that based on which version of MySQL you are using, these functions might be named differently. For example, the MySQL 5.6 PointFromText
function corresponds to MySQL 8.0 ST_PointFromText
function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论