处理动态查询(无法扫描到结构) [英] Handling Dynamic Queries (cant scan into struct)

查看:44
本文介绍了处理动态查询(无法扫描到结构)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用go-pg的情况下,查询的结构是静态的-直接在已知结构中进行查询/扫描就像做梦一样.但是,我正在努力处理动态查询-那些没有结构可扫描的查询.

When using go-pg where the structure of queries is static - querying/scanning directly into a known struct works like a dream. But, I am struggling to handle dynamic queries - ones where there is no struct to scan into.

例如,根据某些运行时参数-查询可能类似于:

For example, depending on some run time parameters - queries could look like:

select foo from table

或者可能是

select foo,bar,baz from table1

select x,y,z from table2

我一直在尝试找出如何将结果加载到地图中.下面的代码引发错误无效的字符'\'寻找值的开头"

I've been trying to figure out how to use load the results into a map. The code below throws an error "invalid character '\' looking for beginning of value"

m := make(map[string]interface{})
_,err:=db.Query(&m, "select foo,bar from table1")
if err!=nil{
   fmt.Println(err)
}

我才刚刚开始学习围棋-完全迷路了.有关如何处理动态查询的任何提示

I'm just starting to learn go - and am totally lost. Any tips on how to handle dynamic queries

推荐答案

您可以通过以下方式实现此目的:首先将数据库行值扫描到一个切片中,然后构建一个保存该行值的映射.

You can achieve this by first scanning the database row values into a slice and subsequently building a map holding the values of the row.

这里是一个示例,其中将查询结果扫描到指向类型为interface {}的变量的指针切片中.

Here is an example where the query results are scanned into an slice of pointers to variables of type interface{}.

sql := "select foo,bar from table1"
rows, err := db.Query(sql)
columns, err := rows.Columns()

// for each database row / record, a map with the column names and row values is added to the allMaps slice 
var allMaps []map[string]interface{}

for rows.Next() {
    values := make([]interface{}, len(columns))
    pointers := make([]interface{}, len(columns))
    for i,_ := range values {
        pointers[i] = &values[i]
    }
    err := rows.Scan(pointers...)
    resultMap := make(map[string]interface{})
    for i,val := range values {
        fmt.Printf("Adding key=%s val=%v\n", columns[i], val)
        resultMap[columns[i]] = val 
    }
    allMaps = append(allMaps, resultMap)
}

为简便起见,不会对任何错误执行错误检查.

For brevity, no error checking is performed on any errors.

这篇关于处理动态查询(无法扫描到结构)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆