标签:where created mysq text limit imp pen close query
//原文链接:https://www.jianshu.com/p/a0569157c418
golang mysql拼接子查询
使用fmt.Sprintf拼接SQL
实例代码
func Select(ids []string) string {
idStr := strings.Join(ids, "','")
sqlText := "select id, name, age, created_at, updated_at from car where id in ('%s') limit %d"
sqlText = fmt.Sprintf(sqlText, idStr, 20)
return sqlText
}
func main() {
sql := Select([]string{"1", "2", "3"})
fmt.Println(sql)
}
//select id, name, age, created_at, updated_at from car where id ('1','2','3') limit 20
另一种写法,占位符实现
import (
"strings"
"database/sql"
)
func Select(db *sql.DB, ids []int) (err error) {
//生成占位符?
sqlText := "select * from car where id in ("+ strings.TrimRight(strings.Repeat("?,", len(ids)), ",")+")"
var args []interface{}
for _, v := range ids {
args = append(args, v)
}
row, err := db.Query(sqlText, args...)
if err != nil {
return
}
defer row.Close()
return
}
标签:where created mysq text limit imp pen close query
原文地址:https://www.cnblogs.com/lajiao/p/11498606.html