course/mysql/sqlx.go

63 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"fmt"
"github.com/jmoiron/sqlx"
"log"
_ "github.com/go-sql-driver/mysql"
)
// sqlx 另外的库
var databasE *sqlx.DB
type users struct {
ID int
NAME string
AGE int
}
func main() {
err := initd()
if err != nil {
return
}
//查询单行不需要scan也能拿到结果
sqlstr := `select id,name,age from user where id=1`
var u users
err = databasE.Get(&u, sqlstr)
if err != nil {
return
}
fmt.Println(u)
//查询多行
var ulist = make([]users, 0, 1) //引用类型初始化
sqlstr2 := `select id,name,age from user`
//必须要传指针
err = databasE.Select(&ulist, sqlstr2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(ulist)
}
func initd() (err error) {
databasE, err = sqlx.Connect("mysql", "root:123456@tcp(43.143.245.135:3306)/user")
if err != nil {
log.Println(err)
return err
}
//connect方法提供了ping。所以不需要ping
//err = databasE.Ping()
//if err != nil {
// log.Println(err)
// return err
//}
log.Println("Successfully connected to mysql")
databasE.SetMaxOpenConns(10)
databasE.SetMaxIdleConns(5)
return nil
}