从PostgreSQL获取列名

时间:2015-12-07 12:54:21

标签: json database postgresql go key

几个月前,我已经开始了我的旅程,所以我还无法找到一些东西。

我有一个朋友帮我建一个api,现在我们正处于项目中间,当时我发现有些东西丢失了。

当我向api发出请求时,不会返回BD中的列名,因此它不会构建正确的json。

有人可以帮我弄清楚我该怎么办?

我有这段代码:

func QueryAndReturnStrings(query string) [][]string {
    var final [][]string
    rows, queryErr := connection.Query(query) // execute our query and get back the rows object from the sql library
    if queryErr != nil {
        log.Fatal(queryErr)
    }

    defer rows.Close() // defer rows.close() so we give our connection back when we’re done
    queryColumns, colErr := rows.Columns()
    if colErr != nil {
        log.Fatal(colErr)
    }

    // Result is your slice string.
    rawResult := make([][]byte, len(queryColumns)) // Then we make rawResult which is an array of array of bytes which is the length of the # of columns in our sql table (that’s pretty important)
    var result []string

    // dest = destination
    dest := make([]interface{}, len(queryColumns)) // A temporary interface{} slice | then we create dest which is an array of interface{}
    // we loop through dest and set it equal to a pointer to the corresponding index in rawResult so we have dest which is an array of pointers to arrays of bytes. (if you don’t really understand pointers, this is going to get really nuts.)
    for i := range rawResult {
        dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
    }

    leng := len(queryColumns)
    count := 0

    for rows.Next() { //  loops through each row in it’s raw sql form
        err := rows.Scan(dest...)
        if err != nil {
            log.Fatal(err)
        }

        for _, raw := range rawResult {
            count++
            if raw == nil {
                result = append(result, "\\N")
            } else {
                result = append(result, string(raw))
            }

            if count == leng {
                count = 0
                final = append(final, result)
                result = nil
            }
        }
    }
    return final
}

0 个答案:

没有答案