go-sql-driver/mysql中Scan結果集轉自動換成map解決方案

jjxuhuade發表於2020-12-20
package main

import (
   "database/sql"
   "fmt"
   "github.com/go-sql-driver/mysql"
   "log"
   "time"
)

var db *sql.DB

func initDb() {
   var err error
   config := mysql.Config{
      User:                 "root",
      Passwd:               "",
      Addr:                 "xxx.xxx.xxx.xxx:3306",
      Net:                  "tcp",
      DBName:               "xxx",
      AllowNativePasswords: true,
   }
   db, err = sql.Open("mysql", config.FormatDSN())
   checkError(err)

   // 設定最大連線數
   db.SetMaxOpenConns(25)
   // 設定最大空閒連線數
   db.SetMaxIdleConns(25)
   // 設定每個連結的過期時間
   db.SetConnMaxLifetime(5 * time.Minute)

   // 嘗試連線,失敗會報錯
   err = db.Ping()
   checkError(err)

}

func checkError(err error) {
   if err != nil {
      log.Fatal(err)
   }
}

func Scan(list *sql.Rows) (rows []map[string]interface{}) {
   fields, _ := list.Columns()
   for list.Next() {
      scans := make([]interface{}, len(fields))
      row := make(map[string]interface{})

      for i := range scans {
         scans[i] = &scans[i]
      }
      list.Scan(scans...)
      for i, v := range scans {
         var value = ""
         if v != nil {
            value = fmt.Sprintf("%s", v)
         }
         row[fields[i]] = value
      }
      rows = append(rows, row)
   }
   return
}

func main() {
   initDb()
   list, _ := db.Query("select * from users")
   defer list.Close()
   rows := Scan(list)
   for _, user := range rows {
      fmt.Println(user["id"], user["name"], user["created_at"])
   }

}

 

結果:

1 admin 2019-05-23 01:54:06
15 jack 2020-01-15 15:43:04
23 測試 2020-03-10 19:20:41
25 測試1 2020-03-21 17:25:42
26 demo2 2020-03-21 18:16:22
27 demo3 2020-03-21 19:08:35
28 user01 2020-03-21 22:50:53
29 user02 2020-03-21 22:52:34
30 li 2020-03-22 13:57:47

 

相關文章