course/mysql/sql_prepare.go

70 lines
1.3 KiB
Go

package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
var dataB *sql.DB
func initDataB() (err error) {
dataB, err = sql.Open("mysql", "root:123456@tcp(43.143.245.135:3306)/wangaodev")
if err != nil {
log.Println(err)
return err
}
err = dataB.Ping()
if err != nil {
log.Println(err)
return err
}
log.Println("Successfully connected to mysql")
dataB.SetMaxOpenConns(10)
dataB.SetMaxIdleConns(5)
return nil
}
type newUser struct {
name string
level string
status int
}
// 预处理方式插入多条数据
func prepareInsert() {
sqlStr := `insert into user (name,level,status) values (?,?,?)`
stmt, err := dataB.Prepare(sqlStr)
if err != nil {
log.Fatal("prepare failed:", err)
}
defer stmt.Close()
//后续只需要拿到stmt去执行一些操作
userData := []newUser{
{name: "Alice", level: "中级", status: 1},
{name: "Bob", level: "高级", status: 2},
{name: "Charlie", level: "初级", status: 0},
}
//循环结构体切片执行
var sum = 0
for _, v := range userData {
ret, err := stmt.Exec(v.name, v.level, v.status)
if err != nil {
return
}
n, _ := ret.RowsAffected()
sum = sum + int(n)
}
fmt.Printf("%v rows has been affected", sum)
}
func main() {
err := initDataB()
if err != nil {
return
}
prepareInsert()
}