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?

图片转代码服务由CSDN问答提供 功能建议

我正在使用以下代码在要构建的API中包装对postgres数据库中的查询的执行

  func QueryDB(qstring字符串)(* sql.Rows){
 psqlInfo:= fmt.Sprintf(“ host =%s port =%d user =%  s dbname =%s sslmode = disable“,主机,端口,用户,dbname)
 db,err:= sql.Open(” postgres“,psqlInfo)
如果err!= nil {
 panic(err)\  n} 
延迟db.Close()
 
 // Ping方法打开连接
 err = db.Ping()
如果err!= nil {
 panic(err)
} 
 \  n //行,错误:= db.Query(“从年龄为$ 1的用户中选择名称,年龄)
 log.Printf(”正在执行SQL%s 
“,qstring)
行,错误:= db  .query(qstring)
 if err!= nil {
 log.Fatal(err)
} 
返回行
} 
   
 
 

我的问题 根据文档,db.Query()方法接受查询strgin,否则接受... interface {}参数。 尝试在我的函数参数中添加第二个参数 params ... interface {},并将params作为第二个参数传递给DB.Query方法,但这不起作用。 仅当我专门从接口切片中拉出参数时,它才似乎起作用。 有任何建议吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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)
    }
    
    点赞 打赏 评论
  • drn34916 2018-07-23 20:55

    I figured it out by lookingin the source code of the SQL module and seeing how it was implemented in the db.Query() method. you add the elipsis to the end of the slice argument to pass it through. Like params...

    点赞 打赏 评论

相关推荐 更多相似问题