course/mysql/mysql_rowquery.go

85 lines
1.9 KiB
Go
Raw Normal View History

2024-07-18 21:48:41 +08:00
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql" //自动执行init()
"log"
)
var db *sql.DB //是一个数据库连接池对象
func initDb() (err error) {
//数据库信息
dsn := "root:123456@tcp(43.143.245.135:3306)/wangaodev"
//连接数据库
db, err = sql.Open("mysql", dsn) //不会校验用户名和密码是否正确
if err != nil {
//dsn 格式不正确会报错
return err
}
//校验用户名和密码是否正确
//尝试连接数据库
err = db.Ping()
if err != nil {
return err
}
log.Printf("connect %s success.\n", dsn)
//设置最大连接数
db.SetMaxOpenConns(10)
//设置最大空闲连接数
db.SetMaxIdleConns(5)
return nil
}
// 表结构对象
type user struct {
2024-07-19 00:07:50 +08:00
id int
name string
level string
status int
2024-07-18 21:48:41 +08:00
}
// 查询单行数据
func queryRow(id int) {
var u user
//查询单行记录的sql语句
2024-07-19 00:07:50 +08:00
sqlstr := "select id,name,level,status from user where id=?"
2024-07-18 21:48:41 +08:00
//执行并且拿到结果
2024-07-19 00:07:50 +08:00
db.QueryRow(sqlstr, id).Scan(&u.id, &u.name, &u.level, &u.status) //从链接池中拿一个连接出来去数据库查询单条记录,scan方法自动释放连接也就是必须调用scan方法
2024-07-18 21:48:41 +08:00
fmt.Printf("user:%#v\n", u)
}
2024-07-19 00:07:50 +08:00
// 查询多行数据
func queryMultiRow(level string) error {
sqlstr := "select id,name,level,status from user where level=?"
rows, err := db.Query(sqlstr, level)
if err != nil {
log.Printf("query multiRow err %v\n", err)
return err
}
//非常重要.关闭rows持有的数据库连接
defer rows.Close()
for rows.Next() {
var u user
err = rows.Scan(&u.id, &u.name, &u.level, &u.status)
if err != nil {
log.Printf("scan err %v\n", err)
return err
}
fmt.Printf("user:%#v\n", u)
}
return nil
}
2024-07-18 21:48:41 +08:00
// go链接mysql示例
func main() {
err := initDb()
if err != nil {
log.Fatalf("init DB failed:%v", err)
}
log.Println("init DB success.")
queryRow(2)
2024-07-19 00:07:50 +08:00
queryMultiRow("L1")
2024-07-18 21:48:41 +08:00
}