dal.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package dal
  2. import (
  3. "fmt"
  4. "xiaoniaokuaiyan.com/xiaoniao/util"
  5. )
  6. type SortParam struct {
  7. SortBy string
  8. SortDir int
  9. }
  10. type ListResult struct {
  11. Totoal int `json:"total"`
  12. PageIndex int `json:"pi"`
  13. PageSize int `json:"ps"`
  14. Data interface{} `json:"data"`
  15. }
  16. func List(result interface{}, tableName, strSql, orderStr, whereStr string, whereValue []interface{}, pinfo Pager) (*ListResult, error) {
  17. count, err := Count("select count(*) as total from "+tableName+" "+whereStr, whereValue)
  18. if err != nil {
  19. return nil, err
  20. }
  21. if count == 0 {
  22. return &ListResult{
  23. Totoal: 0,
  24. PageIndex: pinfo.PageIndex,
  25. PageSize: pinfo.PageSize,
  26. }, nil
  27. }
  28. db := util.GetSqlDB()
  29. if pinfo.PageIndex < 1 {
  30. pinfo.PageIndex = 1
  31. }
  32. if pinfo.PageSize == 0 {
  33. pinfo.PageSize = 10
  34. }
  35. strSql += " " + whereStr + " " + orderStr
  36. strSql += fmt.Sprintf(" limit %d,%d ", (pinfo.PageIndex-1)*pinfo.PageSize, pinfo.PageSize)
  37. //rows, err := db.Queryx(strSql, whereValue...)
  38. err = db.Select(result, strSql, whereValue...)
  39. if err != nil {
  40. return nil, err
  41. }
  42. /*err = util.ScanStructOld(rows.Rows, result)
  43. if err != nil {
  44. return nil, err
  45. }*/
  46. return &ListResult{
  47. Totoal: count,
  48. PageSize: pinfo.PageSize,
  49. PageIndex: pinfo.PageIndex,
  50. Data: result,
  51. }, nil
  52. }
  53. func Count(strSql string, params []interface{}) (int, error) {
  54. db := util.GetSqlDB()
  55. //rows, err := db.NamedQuery(strSql, params)
  56. rows, err := db.Queryx(strSql, params...)
  57. if err != nil {
  58. return 0, err
  59. }
  60. var count int
  61. for rows.Rows.Next() {
  62. rows.Rows.Scan(&count)
  63. }
  64. return count, nil
  65. }