course/mysql/mysql_rowquery.go

85 lines
1.9 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 (
"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 {
id int
name string
level string
status int
}
// 查询单行数据
func queryRow(id int) {
var u user
//查询单行记录的sql语句
sqlstr := "select id,name,level,status from user where id=?"
//执行并且拿到结果
db.QueryRow(sqlstr, id).Scan(&u.id, &u.name, &u.level, &u.status) //从链接池中拿一个连接出来去数据库查询单条记录,scan方法自动释放连接也就是必须调用scan方法
fmt.Printf("user:%#v\n", u)
}
// 查询多行数据
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
}
// go链接mysql示例
func main() {
err := initDb()
if err != nil {
log.Fatalf("init DB failed:%v", err)
}
log.Println("init DB success.")
queryRow(2)
queryMultiRow("L1")
}