一:

在实际的工程项目中,SQL通常使用预编译的形式进行执行操纵,可以有效的防止SQL注入的风险,提高编码的规范性。
golang中使用sqlx进行sql查询的时候,在使用in语句在一个集合中查询的时候,若使用预编译形式则通常有两种形式:
方法一:
使用语言的for语句循环生成SQL语句中的“?”,类似这样:

list:=[]int{,,,}
sql:="select * from books where book_id IN (%s)"
inStatus:=""
params:=make([]interface{},)
for i:=;i<len(list);i++{
if i=={
inStatus+="?"
}else{
inStatus+=",?"
}
params=append(params , list[i])
}
sql = fmt.Sprintf(sql ,inStatus )
db.Exec(sql , params...)

方法二:
其实sqlx内置了一个In()方法用于处理这种情况,可以使得对in的处理十分优雅。
其实该方法的实现和我们方法一的处理原理类似。

// In expands slice values in args, returning the modified query string
// and a new arg list that can be executed by a database. The `query` should
// use the `?` bindVar. The return value uses the `?` bindVar. func In(query string, args ...interface{}) (string, []interface{}, error)

输入的参数query是一个sql语句,其中的需要使用In list的地方使用(?)代替,args为按照前后顺序的查询参数,按照实际对应?的次序的若干个参数。返回值有三个:
第一个,string,是处理完后的sql语句,其中的In查询语句中的一个?已经按照实际的list长度进行处理,替换为多个“?”
第二个,[]interface{},查询参数列表,
第三个,error,错误对象

bookList:=make([]Book , )
sql := "SELECT * FROM books where book_id IN (?) AND status != ? ORDER BY create_time DESC"
ids:=[]int{,,}
sql, args, err := sqlx.In(sql, ids, model.StatusSelfDeleted) //model.StatusSelfDeleted="DELETED"
if err != nil {
return bookList
}
err = db.Select(&bookList, sql, args...) //db为*sqlx.DB类型

其中sqlx.In函数返回的sql如下:

SELECT * FROM books where book_id IN (?,?,?) AND status != ? ORDER BY create_time DESC 

args为:

[,,,"DELETED"]

二:

如果的数组中有两个int,构建它:

SELECT some_column
FROM table_name
WHERE id IN (?, ?)

如果你有四个,构建:

SELECT some_column
FROM table_name
WHERE id IN (?, ?, ?, ?)

等等。你需要的是一个简单的函数,可以产生n占位符; 有很多方法可以做到这一点:

func placeholders(n int) string {
ps := make([]string, n)
for i := ; i < n; i++ {
ps[i] = "?"
}
return strings.Join(ps, ",")
}

或者:

func placeholders(n int) string {
var b strings.Builder
for i := ; i < n - ; i++ {
b.WriteString("?,")
}
if n > {
b.WriteString("?")
}
return b.String()
}
uery := fmt.Sprintf("select some_column from table_name where id in (%s)", placeholders(len(idsToGet)))
rows, err := db.Query(query, idsToGet...)

最新文章

  1. 敏捷转型历程 - Sprint3 Planning
  2. HashSet和TreeSet
  3. VIM退出命令
  4. HDU 1536 S-Nim SG博弈
  5. Linux的IO性能监控
  6. Jeasyframe 开源框架 稳定版 V1.5 发布
  7. 大话设计模式--&gt;模板方法设计模式
  8. hdu4763 KMP
  9. ubuntu下Vim配色方案Solarized的配置
  10. Data URL
  11. jtemplate使用笔记
  12. 去除UINavigationBar默认透明度的方法
  13. Lua开发环境配置
  14. input添加邮箱的时候自动显示后缀
  15. JS学习笔记(三)函数
  16. [js高手之路]一步步图解javascript的原型(prototype)对象,原型链
  17. ios判断手机号是否可用
  18. building tool
  19. 字符串赋值给字符指针(char *a=&quot;hello&quot;)的正确理解方式
  20. Python第4天

热门文章

  1. js 异步编程思想
  2. System.Clollections.ICollection.cs
  3. day23_4_hashlib
  4. niginx相关命令及代理配置
  5. Java之RabbitMQ(二)多mq配置
  6. C# 中的三个高级参数 ref
  7. uboot 的移植过程
  8. oi知识表
  9. UNIX环境高级编程------apue.h找不到
  10. Codeforces 548E Mike ans Foam (与质数相关的容斥多半会用到莫比乌斯函数)