dongpan5289
2017-07-10 07:39
浏览 94

如何使用sqlx共享mysql连接?

I'd like to share sqlx connection to be used in other functions. Here is what I came up with:

 var dbmap = initDb()

 func initDb() *sqlx.DB {         
        db, err := sqlx.Connect("mysql", "myuser:mypasswd@tcp(127.0.0.1:3306)/mydb")        
        if err != nil {
            log.Fatalln(err)
        }        
        // defer db.Close()        
        return db
    }

And then in functions I'd like to make queries like:

var users []User
err := dbmap.Get(&users, "SELECT * FROM user")

However I get panic:

scannable dest type slice with >1 columns (3) in result


2017/07/10 09:32:59 [Recovery] panic recovered:
GET /api/v1/users HTTP/1.1
Host: 127.0.0.1:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
scannable dest type slice with >1 columns (3) in result
/usr/lib/go-1.6/src/runtime/panic.go:443 (0x436179)
    gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/usr/lib/go-1.6/src/log/log.go:320 (0x46a551)
    Panic: panic(s)
/home/me/go/src/myapp/main.go:84 (0x4098bd)
    GetUsers: log.Panic(err)
/home/me/go/src/github.com/gin-gonic/gin/context.go:97 (0x47773a)
    (*Context).Next: c.handlers[c.index](c)
/home/me/go/src/myapp/main.go:54 (0x40b170)
    Cors.func1: c.Next()
/home/me/go/src/github.com/gin-gonic/gin/context.go:97 (0x47773a)
    (*Context).Next: c.handlers[c.index](c)
/home/me/go/src/github.com/gin-gonic/gin/recovery.go:45 (0x489fd1)
    RecoveryWithWriter.func1: c.Next()
/home/me/go/src/github.com/gin-gonic/gin/context.go:97 (0x47773a)
    (*Context).Next: c.handlers[c.index](c)
/home/me/go/src/github.com/gin-gonic/gin/logger.go:63 (0x48926a)
    LoggerWithWriter.func1: c.Next()
/home/me/go/src/github.com/gin-gonic/gin/context.go:97 (0x47773a)
    (*Context).Next: c.handlers[c.index](c)
/home/me/go/src/github.com/gin-gonic/gin/gin.go:284 (0x47e592)
    (*Engine).handleHTTPRequest: context.Next()
/home/me/go/src/github.com/gin-gonic/gin/gin.go:265 (0x47e1c7)
    (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/lib/go-1.6/src/net/http/server.go:2081 (0x60372e)
    serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/lib/go-1.6/src/net/http/server.go:1472 (0x5fffde)
    (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/lib/go-1.6/src/runtime/asm_amd64.s:1998 (0x467171)
    goexit: BYTE    $0x90   // NOP

What's wrong here? How can I fix it?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题