dsf12313 2018-07-05 19:56
浏览 126
已采纳

使用gorm检索没有模型的记录

I have a postgre DB and a little Go api.

The idea of the following func is to retrieve all the records in a json response. I just know the table name, I don't know the field names of the table.

Code:

func indexProductHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    setCors(w)
    //var products []database.Products
    var results []map[string]interface{}

    database.DB.Raw("SELECT * from products").Scan(&results)
    res, err := json.Marshal(results)

    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    w.Write(res)
}

This func will retrieve null values.

Is there a way to retrieve the records without passing the model?

  • 写回答

1条回答 默认 最新

  • dongxixia6399 2018-07-05 22:45
    关注

    As mentioned in the comments for this case there is no need to use gorm, you can retrieve the data with the native sql package.

    After retrieving the data I strongly suggest making a struck for it and using it instead of empty interfaces.

    You can retrieve the data from the products table with like this:

    package main
    
    import (
        "fmt"
        "log"
        "database/sql"
        _ "github.com/lib/pq"
        "encoding/json"
    )
    
    func main() {
        db, err := sql.Open("postgres", "user=USR password=PWD dbname=DBN sslmode=disable")
        checkErr(err)
    
        rows, err := db.Query("SELECT * FROM products")
        checkErr(err)
    
        // Get the column names from the query
        var columns []string
        columns, err = rows.Columns()
        checkErr(err)
    
        colNum := len(columns)
    
        var results []map[string]interface{}
    
        for rows.Next() {
            // Prepare to read row using Scan
            r := make([]interface{}, colNum)
            for i := range r {
                r[i] = &r[i]
            }
    
            // Read rows using Scan
            err = rows.Scan(r...)
            checkErr(err)
    
            // Create a row map to store row's data
            var row = map[string]interface{}{}
            for i := range r {
                row[columns[i]] = r[i]
            }
    
            // Append to the final results slice
            results = append(results, row)
        }
    
        fmt.Println(results) // You can then json.Marshal or w/e
    
        // If you want it pretty-printed
        r, err := json.MarshalIndent(results, "", "  ")
        checkErr(err)
        fmt.Println(string(r))       
    }
    
    func checkErr(err error) {
        if err != nil {
            log.Fatal(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?