栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将“ SELECT *”列读入[]字符串中

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将“ SELECT *”列读入[]字符串中

为了

Scan
将值直接转换为
[]string
,您必须创建一个
[]interface{}
指向字符串切片中每个字符串的切片。

在这里,您有一个适用的MySQL示例(只需更改

sql.Open
-command以匹配您的设置):

package mainimport (    "fmt"    _ "github.com/go-sql-driver/mysql"    "database/sql")func main() {    db, err := sql.Open("mysql", "user:pass@tcp(localhost:3306)/test?charset=utf8")    defer db.Close()    if err != nil {        fmt.Println("Failed to connect", err)        return    }    rows, err := db.Query(`SELECT 'one' col1, 'two' col2, 3 col3, NULL col4`)    if err != nil {        fmt.Println("Failed to run query", err)        return    }    cols, err := rows.Columns()    if err != nil {        fmt.Println("Failed to get columns", err)        return    }    // Result is your slice string.    rawResult := make([][]byte, len(cols))    result := make([]string, len(cols))    dest := make([]interface{}, len(cols)) // A temporary interface{} slice    for i, _ := range rawResult {        dest[i] = &rawResult[i] // Put pointers to each string in the interface slice    }    for rows.Next() {        err = rows.Scan(dest...)        if err != nil { fmt.Println("Failed to scan row", err) return        }        for i, raw := range rawResult { if raw == nil {     result[i] = "\N" } else {     result[i] = string(raw) }        }        fmt.Printf("%#vn", result)    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/471052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号