新增:
// 插入数据
func insertData() {
sqlStr := "insert into user_tbl(username,password) values (?,?)"
ret, err := db.Exec(sqlStr, "张三", "zs123")
if err != nil {
fmt.Printf("insert failed, err:%v\n", err)
return
}
theID, err := ret.LastInsertId() // 新插入数据的id
if err != nil {
fmt.Printf("get lastinsert ID failed, err:%v\n", err)
return
}
fmt.Printf("insert success, the id is %d.\n", theID)
}
删除:
func delData() {
sql := "delete from user_tbl where id =?"
ret, err := db.Exec(sql, "1")
if err != nil {
fmt.Printf("删除失败, err:%v\n", err)
return
}
rows, err := ret.RowsAffected()
if err != nil {
fmt.Printf("删除行失败, err:%v\n", err)
return
}
fmt.Printf("删除成功, 删除的行数:%d.\n", rows)
}
更新:
func updateData() {
sql := "update user_tbl set username=?, password=? where id=?"
ret, err := db.Exec(sql, "kite2", "kite123", "2")
if err != nil {
fmt.Printf("更新失败, err:%v\n", err)
return
}
rows, err := ret.RowsAffected()
if err != nil {
fmt.Printf("更新行失败, err:%v\n", err)
return
}
fmt.Printf("更新成功, 更新的行数:%d.\n", rows)
}