dptn69182 2018-02-05 19:38
浏览 49
已采纳

执行查询时是否可以传递参数数组而不是单独传递每个参数?

Does anyone know if its possible to pass in an array of parameters when you are executing a query instead of each parameter individually? So instead of:

query = “select * from grid where test1 = ? AND test2 = ?”
g.DB.Query(query, params[0], params[1])

Something like:

query = “select * from grid where test1 = ? AND test2 = ?”
g.DB.Query(query, params)

I tried unpacking the slice like this:

g.DB.Query(query, params...)

But got the error:

cannot use parameters (type []string) as type []interface {} in argument to g.DB.Query

  • 写回答

1条回答 默认 最新

  • duanlian1978 2018-02-05 23:07
    关注

    You almost have it. You just need to have params as an []interface{} instead of []string. Something more like this:

    var params []interface{}
    params = append(params, strs[0], strs[1])
    

    or perhaps:

    params := make([]interface{}, len(strs))
    for i, s := range strs {
        params[i] = s
    }
    

    if you don't know ahead of time how many strings you'll have. Then later you can unpack/splat your params slice:

    g.DB.Query(query, params...)
    

    and it'll work as this version of params will have the right type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致