go-sql-driver/mysql中Scan結果集轉自動換成map解決方案
阿新 • • 發佈:2020-12-21
技術標籤:GO
package main import ( "database/sql" "encoding/json" "fmt" "github.com/go-sql-driver/mysql" "log" "strconv" "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, ParseTime: false, } 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]string) { fields, _ := list.Columns() //types,_:= list.ColumnTypes() //for _,b:=range types{ // fmt.Println(b.DatabaseTypeName()) //} //fmt.Printf("%T",types) for list.Next() { scans := make([]interface{}, len(fields)) row := make(map[string]string) for i := range scans { scans[i] = &scans[i] } list.Scan(scans...) for i, v := range scans { var value string 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 { var id, _ = strconv.Atoi(user["id"]) var status, _ = strconv.ParseBool(user["status"]) // 將日期字串解析為Go的time物件第一個引數指定格式,第二個是日期字串 const timeLayout = "2006-01-02 15:04:05" const timeLayout1 = "2006-01-02" const timeLayout2 = "15:04:05" myDate, _ := time.Parse(timeLayout, user["created_at"]) UserIns := struct { Id int Name string CreatedAt string RememberToken string Status bool }{ id, user["name"], myDate.Format(timeLayout2), user["remember_token"], status, } jsonData, _ := json.Marshal(UserIns) json := string(jsonData) fmt.Println(UserIns) fmt.Println(json) } }
結果:
{1 admin 01:54:06 zHHWp9NOQ28fiROUlZcHM31WaLfeg1QQnNenLcLUYNLLj5SsHEZOI06GWMcU true}
{"Id":1,"Name":"admin","CreatedAt":"01:54:06","RememberToken":"zHHWp9NOQ28fiROUlZcHM31WaLfeg1QQnNenLcLUYNLLj5SsHEZOI06GWMcU","Status":true}
{"Id":15,"Name":"jack","CreatedAt":"15:43:04","RememberToken":"ovjdd4nJyAFJ1hCHfTHb7bQPnsU3uMwTXNnRgVkHvFluGUpapoGxf0i5Cg5P","Status":true}
{"Id":23,"Name":"測試","CreatedAt":"19:20:41","RememberToken":"NjZBZ47d0dAAnvW7ekhuIvedMbWl42Gq32aSIVjCjYWcz2eFOlndUEOPgY00","Status":true}
{25 測試1 17:25:42 true}
{"Id":25,"Name":"測試1","CreatedAt":"17:25:42","RememberToken":"","Status":true}
{26 demo2 18:16:22 true}
{"Id":26,"Name":"demo2","CreatedAt":"18:16:22","RememberToken":"","Status":true}
{27 demo3 19:08:35 false}
{"Id":27,"Name":"demo3","CreatedAt":"19:08:35","RememberToken":"","Status":false}
{28 user01 22:50:53 false}
{"Id":28,"Name":"user01","CreatedAt":"22:50:53","RememberToken":"","Status":false}
{29 user02 22:52:34 false}
{"Id":29,"Name":"user02","CreatedAt":"22:52:34","RememberToken":"","Status":false}
{30 li 13:57:47 false}
{"Id":30,"Name":"li","CreatedAt":"13:57:47","RememberToken":"","Status":false}