gpt4 book ai didi

sql - Go SQL扫描的行被覆盖

转载 作者:IT王子 更新时间:2023-10-29 01:42:36 25 4
gpt4 key购买 nike

我正在尝试从 SQL 服务器上的表中读取所有行,并将它们存储在字符串 slice 中以备后用。我遇到的问题是每次扫描新行时以前扫描的行都会被覆盖,即使我已经将所有可变字节 slice 转换为不可变字符串并将结果 slice 保存到另一个 slice 。这是我正在使用的代码:

rawResult := make([]interface{}, len(cols)) // holds anything that could be in a row
result := make([]string, len(cols)) // will hold all row elements as strings
var results [][]string // will hold all the result string slices
dest := make([]interface{}, len(cols)) // temporary, to pass into scan
for i, _ := range rawResult {
dest[i] = &rawResult[i] // fill dest with pointers to rawResult to pass into scan
}
for rows.Next() { // for each row
err = rows.Scan(dest...) // scan the row
if err != nil {
log.Fatal("Failed to scan row", err)
}
for i, raw := range rawResult { // for each scanned byte slice in a row
switch rawtype := raw.(type){ // determine type, convert to string
case int64:
result[i] = strconv.FormatInt(raw.(int64), 10)
case float64:
result[i] = strconv.FormatFloat(raw.(float64), 'f', -1, 64)
case bool:
result[i] = strconv.FormatBool(raw.(bool))
case []byte:
result[i] = string(raw.([]byte))
case string:
result[i] = raw.(string)
case time.Time:
result[i] = raw.(time.Time).String()
case nil:
result[i] = ""
default: // shouldn't actually be reachable since all types have been covered
log.Fatal("Unexpected type %T", rawtype)
}
}
results = append(results, result) // append the result to our slice of results
}

我确信这与 Go 处理变量和内存的方式有关,但我似乎无法修复它。有人可以解释一下我不明白的地方吗?

最佳答案

您应该为每个数据行创建新 slice 。请注意,一个 slice 有一个指向底层数组的指针,因此您添加到 results 中的每个 slice 在实际数据数组上都有相同的指针。这就是您遇到这种行为的原因。

关于sql - Go SQL扫描的行被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com