doutuan6158 2015-12-07 12:54
浏览 151

从PostgreSQL获取列名

I've started my journey with the lang a couple of months ago, so I can't figure out some stuff yet.

I had a friend help me building an api, and now we are in the middle of the project when I noticed something was missing.

When I make a request to the api, the column name from the BD is not returned, so it doesn't build a correct json.

Can someone help me figure out how can I do it?

I have this code:

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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 对于知识的学以致用的解释
    • ¥50 三种调度算法报错 有实例
    • ¥15 关于#python#的问题,请各位专家解答!
    • ¥200 询问:python实现大地主题正反算的程序设计,有偿
    • ¥15 smptlib使用465端口发送邮件失败
    • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
    • ¥15 对于squad数据集的基于bert模型的微调
    • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
    • ¥20 steam下载游戏占用内存
    • ¥15 CST保存项目时失败