gpt4 book ai didi

mysql - 将 “SELECT *” 列(多于一个)读入 [][]string in go

转载 作者:数据小太阳 更新时间:2023-10-29 03:08:27 25 4
gpt4 key购买 nike

我想在 Go 中将 MySQL 数据库列插入到 [][]string 中,这是一个类似的代码,它只对一列执行此操作并将其插入到 []string 中,但我需要更多列到 [][]string 中制作数据框。

mysql> select * from users;
+----+-----------+----------+----------+-------------------------------+--------------+
| id | fname | lname | uname | email | contact |
+----+-----------+----------+----------+-------------------------------+--------------+
| 1 | Rishikesh | Agrawani | hygull | rishikesh0014051992@gmail.com | 917353787704 |
| 2 | Sandeep | E | sandeep | sandeepeswar8@gmail.com | 919739040038 |
| 3 | Darshan | Sidar | darshan | sidardarshan@gmail.com | 917996917565 |
| 4 | Surendra | Prajapat | surendra | surendrakgadwal@gmail.com | 918385894407 |
| 5 | Mukesh | Jakhar | mukesh | mjakhar.kjahhar@gmail.com | 919772254140 |
+----+-----------+----------+----------+-------------------------------+--------------+
5 rows in set (0.00 sec)

mysql>
func main() {
// db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>?charset=utf8" )
db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")

if err != nil {
log.Fatal(err)
}

rows, err := db.Query("select fname from users")

if err != nil {
log.Fatal(err)
}

firstnames:=[]string{}
for rows.Next() {
var fname string
rows.Scan(&fname)
firstnames = append(firstnames, fname)
}

fmt.Println(firstnames)
db.Close()
}

最佳答案

假设您的查询返回 4 列,您只需一次扫描多个值。

details:=[][]string{}
for rows.Next() {
cols := make([]string, 4)
rows.Scan(&cols[0], &cols[1], &cols[2], &cols[3])
details = append(details, cols)
}

如果列数不是静态的,你可以做这样的事情来自动化它,而不是手动扩展指针:

details:=[][]string{}
for rows.Next() {
cols := make([]string, num_cols)
// Create an array of string pointers pointing to the column strings.
col_ptrs = make([]*string, num_cols)
for i := 0; i < num_cols; i++ {
col_ptrs[i] = &cols[i];
}
rows.Scan(col_ptrs...)
details = append(details, cols)
}

关于mysql - 将 “SELECT *” 列(多于一个)读入 [][]string in go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929295/

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