dougourang1856 2018-07-23 20:49
浏览 74
已采纳

Postgres中的Golang包装查询执行

I am using the following code to wrap execution of aquery on a postgres database in a API I am building just to learn Go.

func QueryDB(qstring string) (*sql.Rows) {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable", host, port, user, dbname)
    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
      panic(err)
    }
    defer db.Close()

    //Ping method opens the connection
    err = db.Ping()
    if err != nil {
       panic(err)
    }

    //rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)
    log.Printf("executing SQL %s
",qstring)
    rows, err := db.Query(qstring)
    if err != nil {
       log.Fatal(err)
    }
    return rows
}

my question is as per the documentation the db.Query() method accepts a query strgin and ...interface{} arguments otherwise. tried adding a second argument params ...interface{} to my function arguments and passing params as the second argument to the DB.Query method, and this doesn't work. it only seems to work if I specifically pull the arguments out of the interface slice. Any suggestions?

  • 写回答

2条回答 默认 最新

  • drfrvbq736383 2018-07-23 23:19
    关注

    This may help you

    Variadic functions can be called in the usual way with individual arguments. If you already have multiple args in a slice, apply them to a variadic function using func(slice...)

    If you want send data from an slice, just add elipsis:

    rows, err := db.Query(qstring, data...)
    if err != nil {
       log.Fatal(err)
    }
    

    If you has the values separated in different variables:

    rows, err := db.Query(qstring, val1, val2, val3, valN)
    if err != nil {
       log.Fatal(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。