golang操作MySQL的具体案例
golang操作MySQL的具体案例
代码篇的基础操作:
package mainimport ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx")type Profile struct { Id int `db:"id"` Student string `db:"student"`}var Db *sqlx.DBfunc init() { database, err :=sqlx.Open("mysql","root:1234567890@tcp(127.0.0.1:3306)/Demo") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database}func main() { // 添加 r, err := Db.Exec("insert into profile(student)values(?)", "stu001") if err != nil { fmt.Println("exec failed, ", err) return } id, err := r.LastInsertId() if err != nil { fmt.Println("exec failed, ", err) return } var profile []Profile // 查 selectErr := Db.Select(&profile,"select id,student from profile where id=?",1) if selectErr != nil { fmt.Println("exec failed, ", selectErr) return } fmt.Println("select succ:", profile) //更新 res, resErr := Db.Exec("update profile set student=? where id=?", "stu0003", 1) if resErr != nil { fmt.Println("exec failed, ", resErr) return } row, rowErr := res.RowsAffected() if rowErr != nil { fmt.Println("rows failed, ",rowErr) } fmt.Println("update succ:",row) // 删除 delres, delerr := Db.Exec("delete from profile where id=?", 1) if delerr != nil { fmt.Println("exec failed, ", delerr) return } delrow,delrowerr := delres.RowsAffected() if delrowerr != nil { fmt.Println("rows failed, ",delrowerr) } fmt.Println("delete succ: ",delrow) defer Db.Close() // 注意这行代码要写在上面err判断的下面}
结果:
╰$ go run mySql.go exec failed, 4 select succ: [] update succ: 0 delete succ: 0
赞 (0)