使用go-pg时查询的结构是静态的-直接在已知结构中进行查询/扫描就像做梦一样。但是,我正在努力处理动态查询-那些没有结构可扫描的查询。
例如,根据某些运行时参数-查询可能类似于:
select foo from table
或者可能是
select foo,bar,baz from table1
或
select x,y,z from table2
我一直在尝试找出如何将结果加载到地图中。下面的代码引发错误“无效字符'\'寻找值的开头”
m := make(map[string]interface{})
_,err:=db.Query(&m, "select foo,bar from table1")
if err!=nil{
fmt.Println(err)
}
我刚刚开始学习围棋-完全迷路了。有关如何处理动态查询的任何提示
答案 0 :(得分:1)
您可以通过以下方式实现此目的:首先将数据库行值扫描到一个切片中,然后构建一个保存该行值的映射。
这里是一个示例,其中将查询结果扫描到指向类型为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)
}
为简便起见,不对任何错误执行错误检查。