1. Delete操作

  1. package main
  2. import (
  3. "fmt"
  4. _ "github.com/go-sql-driver/mysql"
  5. "github.com/jmoiron/sqlx"
  6. )
  7. type Person struct {
  8. UserId int `db:"user_id"`
  9. Username string `db:"username"`
  10. Sex string `db:"sex"`
  11. Email string `db:"email"`
  12. }
  13. type Place struct {
  14. Country string `db:"country"`
  15. City string `db:"city"`
  16. TelCode int `db:"telcode"`
  17. }
  18. var Db *sqlx.DB
  19. func init() {
  20. database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test")
  21. if err != nil {
  22. fmt.Println("open mysql failed,", err)
  23. return
  24. }
  25. Db = database
  26. }
  27. func main() {
  28. /*
  29. _, err := Db.Exec("delete from person where user_id=?", 1)
  30. if err != nil {
  31. fmt.Println("exec failed, ", err)
  32. return
  33. }
  34. */
  35. res, err := Db.Exec("delete from person where user_id=?", 1)
  36. if err != nil {
  37. fmt.Println("exec failed, ", err)
  38. return
  39. }
  40. row,err := res.RowsAffected()
  41. if err != nil {
  42. fmt.Println("rows failed, ",err)
  43. }
  44. fmt.Println("delete succ: ",row)
  45. }

运行结果:

第一次运行:

  1. delete succ: 1
  2. #受影响的行数 1

第二次运行:

  1. delete succ: 0
  2. #受影响的行数 0