猿问

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

我想编写一个Go程序,以使用将数据库表中的行转储到csv文件中SELECT *

Go提供了出色的sqlcsv api,但是csv希望根据它们的类型ScanRows“填充”字段中使用字符串数组和方法。由于我以前不知道该表,所以我不知道有多少列以及它们的类型是什么。

这是我在 Go 中的第一个程序,所以我有点挣扎。

如何最好地将Rows实例中的列读入[]string-,这是“正确”的方式吗?

谢谢!


慕桂英3389331
浏览 229回答 3
3回答

哈士奇WWW

以下代码完全符合您的要求,您可以从https://gist.github.com/hygull/645c3dc39c69b6b69c06f5ea9deee41f获取此代码。还提供了表格数据。/**&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "created_on": "26 may 2017",&nbsp; &nbsp; &nbsp; &nbsp; "todos": [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "go get github.com/go-sql-driver/mysql"&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp; "aim": "Reading fname column into []string(slice of strings)"&nbsp; &nbsp; }*//*&nbsp;mysql> select * from users;+----+-----------+----------+----------+-------------------------------+--------------+| id | fname&nbsp; &nbsp; &nbsp;| lname&nbsp; &nbsp; | uname&nbsp; &nbsp; | email&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| contact&nbsp; &nbsp; &nbsp; |+----+-----------+----------+----------+-------------------------------+--------------+|&nbsp; 1 | Rishikesh | Agrawani | hygull&nbsp; &nbsp;| rishikesh0014051992@gmail.com | 917353787704 ||&nbsp; 2 | Sandeep&nbsp; &nbsp;| E&nbsp; &nbsp; &nbsp; &nbsp; | sandeep&nbsp; | sandeepeswar8@gmail.com&nbsp; &nbsp; &nbsp; &nbsp;| 919739040038 ||&nbsp; 3 | Darshan&nbsp; &nbsp;| Sidar&nbsp; &nbsp; | darshan&nbsp; | sidardarshan@gmail.com&nbsp; &nbsp; &nbsp; &nbsp; | 917996917565 ||&nbsp; 4 | Surendra&nbsp; | Prajapat | surendra | surendrakgadwal@gmail.com&nbsp; &nbsp; &nbsp;| 918385894407 ||&nbsp; 5 | Mukesh&nbsp; &nbsp; | Jakhar&nbsp; &nbsp;| mukesh&nbsp; &nbsp;| mjakhar.kjahhar@gmail.com&nbsp; &nbsp; &nbsp;| 919772254140 |+----+-----------+----------+----------+-------------------------------+--------------+5 rows in set (0.00 sec)mysql>&nbsp;*/package mainimport "fmt"import "log"import (&nbsp; &nbsp; _"github.com/go-sql-driver/mysql"&nbsp; &nbsp;&nbsp; &nbsp; "database/sql")func main() {&nbsp; &nbsp; // db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>?charset=utf8" )&nbsp; &nbsp; db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; rows, err := db.Query("select fname from users")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; firstnames := []string{}&nbsp; &nbsp; for rows.Next() {&nbsp; &nbsp; &nbsp; &nbsp; var fname string&nbsp; &nbsp; &nbsp; &nbsp; rows.Scan(&fname)&nbsp; &nbsp; &nbsp; &nbsp; firstnames = append(firstnames, fname)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(firstnames)&nbsp; &nbsp; db.Close()}/*&nbsp;[Rishikesh Sandeep Darshan Surendra Mukesh]*/
随时随地看视频慕课网APP

相关分类

Go
我要回答