1. Select操作

  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. var person []Person
  29. err := Db.Select(&person, "select user_id, username, sex, email from person where user_id=?", 1)
  30. if err != nil {
  31. fmt.Println("exec failed, ", err)
  32. return
  33. }
  34. fmt.Println("select succ:", person)
  35. }

输出结果:

  1. select succ: [{1 stu001 man stu01@qq.com}]