go 拼接sql
Posted lajiao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go 拼接sql相关的知识,希望对你有一定的参考价值。
//原文链接: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
以上是关于go 拼接sql的主要内容,如果未能解决你的问题,请参考以下文章