一、安装sqlx
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql" //初始化
"github.com/jmoiron/sqlx"
)
//创建与数据库映射的结构体
type user struct {
Id int
Name string
Age int
}
//创建一个全局对象
var pool *sqlx.DB
func InItDB() (err error) {
dsn := "root:123456@tcp(127.0.0.1:3306)/db02?charset=utf8mb4&parseTime=True&loc=Local"
//创建数据库对象
pool, err = sqlx.Connect("mysql", dsn)
if err != nil {
fmt.Println("pool err:",err)
return err
}
//设置连接池最大连接数
pool.SetMaxOpenConns(50)
//设置连接池最大空闲连接数
pool.SetMaxIdleConns(10)
return nil
}
func main() {
InItDB()
//查询单行数据
sqlStr := "select id,name,age from user where id=?"
var u user
//查询数据
err := pool.Get(&u, sqlStr,8)
if err != nil {
fmt.Println("get err:",err)
return
}
fmt.Println(u)
//查询多行数据
sqlStr = "select id,name,age from user where id>?"
var v []user
err = pool.Select(&v, sqlStr, 0)
if err != nil {
fmt.Println("select err:",err)
return
}
fmt.Println(v)
}