zoukankan      html  css  js  c++  java
  • golang获取数据表转换为json通用方法

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
        "net/http"
        "time"
    
        _ "github.com/go-sql-driver/mysql"
    )
    import "strings"
    
    func main() {
        http.HandleFunc("/getuser", getuser)
        s := &http.Server{
            Addr:           ":7080",
            ReadTimeout:    30 * time.Second,
            WriteTimeout:   30 * time.Second,
            MaxHeaderBytes: 1 << 20,
        }
        log.Fatal(s.ListenAndServe())
    }
    
    func getuser(w http.ResponseWriter, r *http.Request) {
    
        w.Write([]byte(getuser_json()))
    }
    
    func getuser_json() string {
        db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/jeecg?charset=utf8")
        if err != nil {
            panic(err.Error())
        }
        defer db.Close()
    
        rows, err := db.Query("select * from t_s_user")
        if err != nil {
            panic(err.Error())
        }
    
        columns, err := rows.Columns()
        if err != nil {
            panic(err.Error())
        }
    
        values := make([]sql.RawBytes, len(columns))
    
        scanArgs := make([]interface{}, len(values))
    for i := range values {
            scanArgs[i] = &values[i]
        }
    
        list := "["
    
        for rows.Next() {
            err = rows.Scan(scanArgs...)
            if err != nil {
                fmt.Println("log:", err)
                panic(err.Error())
            }
    
            row := "{"
            var value string
            for i, col := range values {
                if col == nil {
                    value = "NULL"
                } else {
                    value = string(col)
                }
    
                columName := strings.ToLower(columns[i])
    
                cell := fmt.Sprintf(`"%v":"%v"`, columName, value)
                row = row + cell + ","
            }
            row = row[0 : len(row)-1]
            row += "}"
            list = list + row + ","
    
        }
        list = list[0 : len(list)-1]
        list += "]"
        fmt.Println(list)
        return list
    }

    调用url : http://localhost:7080/getuser

  • 相关阅读:
    Kendo
    过河
    数组分组(简单dp)
    Codeforces Round #604 (Div. 2)(A-E)
    HDU1253
    HDU1026
    linux常用命令(二) --目录操作
    linux常用命令(一)--ls
    hdu 1072
    Codeforces Round #597 (Div. 2)(A-D)
  • 原文地址:https://www.cnblogs.com/coolyylu/p/5831720.html
Copyright © 2011-2022 走看看