将“ SELECT *”列(不止一列)读入[] []字符串中

I want to insert MySQL database columns into [][]string in Go, here is a similar code which do this for only one column and insert it into []string but I need more columns into [][]string to make a data frame.

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()
}

Suppose your query returns 4 columns, you just scan multiple values at once.

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

If the number of columns is not static, you can do something like this to automate it, instead of expanding the pointers manually:

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)
}