course/mysql/mysql_insert_update_delete.go

92 lines
1.8 KiB
Go
Raw Normal View History

2024-07-19 00:07:50 +08:00
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
var database *sql.DB
func initDataBase() (err error) {
database, err = sql.Open("mysql", "root:123456@tcp(43.143.245.135:3306)/wangaodev")
if err != nil {
return err
}
err = database.Ping()
if err != nil {
return err
}
log.Println("Successfully connected to mysql")
database.SetMaxOpenConns(10)
database.SetMaxIdleConns(5)
return nil
}
// 插入数据
func insert(name, level string, status int) {
//1.写sql语句
sqlStr := `insert into user (name,level,status) values (?,?,?)`
//2.exec
ret, err := database.Exec(sqlStr, name, level, status)
if err != nil {
log.Println("insert error:", err)
return
}
//如果是插入数据的操作能够拿到插入数据的id
id, err := ret.LastInsertId()
if err != nil {
log.Println("get id failed:", err)
return
}
log.Println("id:", id)
}
// 更新数据
func update(name string, id int) {
//1.写sql语句
sqlStr := `update user set name=? where id=?`
//2.exec
ret, err := database.Exec(sqlStr, name, id)
if err != nil {
log.Println("insert error:", err)
return
}
//如果是插入数据的操作能够拿到插入数据的id
affectedNum, err := ret.RowsAffected()
if err != nil {
log.Println("update row failed:", err)
return
}
log.Println("affectedNum:", affectedNum)
}
//删除数据
func deleteRow(id int) {
sqlStr := `delete from user where id=?`
ret, err := database.Exec(sqlStr, id)
if err != nil {
log.Println("delete error:", err)
}
rowsAffected, err := ret.RowsAffected()
if err != nil {
log.Println("delete row failed:", err)
}
log.Println("rowsAffected:", rowsAffected)
}
func main() {
err := initDataBase()
if err != nil {
log.Fatalf("connect mysql failed,error:%v", err)
return
}
//insert("尹晨旭", "L2", 0)
//update("吴斌", 19)
deleteRow(19)
}