发现了一个不错的包,地址为:https://github.com/hopehook/golang-db
大致把mysql 连接池封装了起来,看着很不错的样子
我尝试了一下,查询为空,不知道为什么,那位高人给看看:
my main package:
```
package main
import(
"github.com/gin-gonic/gin"
"net/http"
"fecshop.com/module/user"
//"fecshop.com/common/cdb"
_ "github.com/go-sql-driver/mysql"
mysqlPool "github.com/hopehook/golang-db/mysql"
)
func mysqlDBPool() *mysqlPool.SQLConnPool{
host := `127.0.0.1:3306`
database := `go_test`
user := `root`
password := `xxx`
charset := `utf8`
// 用于设置最大打开的连接数
maxOpenConns := 200
// 用于设置闲置的连接数
maxIdleConns := 100
mysqlDB := mysqlPool.InitMySQLPool(host, database, user, password, charset, maxOpenConns, maxIdleConns)
return mysqlDB
}
func main() {
mysqlDB := mysqlDBPool();
r := gin.Default()
v2 := r.Group("/v2")
{
// 查询部分
v2.GET("/users", func(c *gin.Context) {
data := user.List2(mysqlDB);
c.JSON(http.StatusOK, data)
})
}
r.Run("120.24.37.249:3000") // listen and serve on 0.0.0.0:8080
}
```
my user package code :
```
package user
import (
"fmt"
"github.com/gin-gonic/gin"
mysqlPool "github.com/hopehook/golang-db/mysql"
)
func List2(mysqlDB *mysqlPool.SQLConnPool) gin.H{
body := make(gin.H)
rows, err := mysqlDB.Query("SELECT * From user")
if err != nil {
fmt.Printf("%s\r\n","mysql query error")
}
fmt.Printf("%v\r\n",rows)
var dbdata []gin.H
if rows != nil {
for _, row := range rows {
h := make(gin.H)
for k,v := range row {
h[k] = v
}
dbdata = append(dbdata, h)
}
}
body["data"] = dbdata
return body
}
```
`fmt.Printf("%v\r\n",rows)` :
```
[map[] map[] map[] map[] map[] map[] map[] map[] map[]]
```
return empty
go_test.user:
```
CREATE TABLE IF NOT EXISTS `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT '',
`age` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
--
-- 转存表中的数据 `user`
--
INSERT INTO `user` (`id`, `name`, `age`) VALUES
(1, '111', 111),
(2, 'terry', 44),
(3, 'terry', 55),
(4, 'terry', 44),
(5, 'terry', 44),
(6, 'terry', 44),
(7, 'terry', 44),
(8, 'te11rry', 929),
(10, 'terry', 66);
```
can you help me ? thank you!
更多评论