亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go SQL 掃描的行被覆蓋

Go SQL 掃描的行被覆蓋

Go
一只甜甜圈 2021-10-25 14:33:57
我正在嘗試從 SQL 服務器上的表中讀取所有行,并將它們存儲在字符串切片中以供以后使用。我遇到的問題是,每次掃描新行時,以前掃描的行都會被覆蓋,即使我已將所有可變字節切片轉換為不可變字符串并將結果切片保存到另一個切片。這是我正在使用的代碼:rawResult := make([]interface{}, len(cols)) // holds anything that could be in a rowresult := make([]string, len(cols)) // will hold all row elements as stringsvar results [][]string // will hold all the result string slicesdest := make([]interface{}, len(cols)) // temporary, to pass into scanfor 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 處理變量和內存的方式有關,但我似乎無法修復它。有人可以解釋我不理解的內容嗎?
查看完整描述

3 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

您應該為每個數據行創建新切片。請注意,切片有一個指向底層數組的指針,因此您添加的每個切片results在實際數據數組上都有相同的指針。這就是你面對這種行為的原因。


查看完整回答
反對 回復 2021-10-25
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

移動result := make([]string, len(cols))到您的for循環,循環通過可用行。


查看完整回答
反對 回復 2021-10-25
  • 3 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號