英文:
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...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论