1. Insert操作

  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. r, err := Db.Exec("insert into person(username, sex, email)values(?, ?, ?)", "stu001", "man", "stu01@qq.com")
  29. if err != nil {
  30. fmt.Println("exec failed, ", err)
  31. return
  32. }
  33. id, err := r.LastInsertId()
  34. if err != nil {
  35. fmt.Println("exec failed, ", err)
  36. return
  37. }
  38. fmt.Println("insert succ:", id)
  39. }