如何使用gorm将POINT插入到mysql中?

huangapple go评论87阅读模式
英文:

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特定的函数,如GeomFromTextPointFromText,将字符串转换为空间数据类型。

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.

huangapple
  • 本文由 发表于 2022年11月2日 00:10:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/74278698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定