MySQL转义字符串

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

MySQL escape string

问题

如何过滤来自URL参数的输入示例
localhost:8080/v1/data/:id

我想在Golang中使用类似于mysql_real_escape_string的过滤器来过滤id参数,我不能使用?,因为这个过滤器是动态的,这个参数可以使用也可以不使用,就像这个例子一样:

if status != "99" {
    where = append(where, "vs.stats = '1'")
}

if cari != "" {
    where = append(where, "(lm.title_member like '%"+cari+"%' OR " +
        "lm.nama_member like '%"+cari+"%' )")
}

query := "select vs.*, lm.nama_member from volks_shift vs left join list_member lm on vs.id_m=lm.id_m where vs.id_s=?"

rows, err := s.DB.QueryContext(ctx, query, id_s)

我希望安全地处理cari值,而不使用?

英文:

How can I filter input from URL param example
localhost:8080/v1/data/:id

And I want to use filter like mysql_real_escape_string param for id in Golang, I can't use ? cause this filter is dynamic, this param can be use or no, like this example

if status != "99" {
	where = append(where, "vs.stats = '1'")
}

if cari != "" {
	where = append(where, "(lm.title_member like '%"+cari+"%' OR " +
	"lm.nama_member like '%"+cari+"%' )")
}

query := "select vs.*, lm.nama_member from volks_shift vs left join list_member lm on vs.id_m=lm.id_m where vs.id_s=?"

rows, err := s.DB.QueryContext(ctx, query, id_s)

and I want secure cari val, without use ?

答案1

得分: 0

database/sql包中没有逃逸函数,可以参考相关问题#18478(在使用数据库抽象层时调用特定于MySQL的函数也不好)。

但是实际上并不需要逃逸函数,你仍然可以在动态查询中使用?。只需动态地与查询一起构建查询参数,像这样:

	query := "SELECT vs.*, lm.nama_member" +
		" FROM volks_shift vs LEFT JOIN list_member lm ON vs.id_m=lm.id_m" +
		" WHERE vs.id_s=?"
	params := []interface{}{id_s}

	if status != "99" {
		query += " AND vs.stats = '1'"
	}

	if cari != "" {
		query += " AND (lm.title_member LIKE ? OR lm.nama_member LIKE ?)"
		params = append(params, "%"+cari+"%", "%"+cari+"%")
	}

	rows, err := s.DB.QueryContext(ctx, query, params...)
英文:

There is no escape function in the database/sql package, see related issue #18478 (and it's also not nice to invoke a mysql-specific function when using a database abstraction layer).

But it is also not needed as you can still use ? in a dynamic query. Just build the query parameters dynamically together with the query, like so:

	query := "SELECT vs.*, lm.nama_member" +
		" FROM volks_shift vs LEFT JOIN list_member lm ON vs.id_m=lm.id_m" +
		" WHERE vs.id_s=?"
	params := []interface{}{id_s}

	if status != "99" {
		query += " AND vs.stats = '1'"
	}

	if cari != "" {
		query += " AND (lm.title_member LIKE ? OR lm.nama_member LIKE ?)"
		params = append(params, "%"+cari+"%", "%"+cari+"%")
	}

	rows, err := s.DB.QueryContext(ctx, query, params...)

huangapple
  • 本文由 发表于 2021年8月25日 12:05:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68916609.html
匿名

发表评论

匿名网友

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

确定