文章目录
- 1 基本结构
- 1.1 数据
- 1.2 数据结构
- 2 代码
- 3 tip
1 基本结构
1.1 数据
1.2 数据结构
2 代码
- 代码:
package mainimport ("database/sql""encoding/csv""fmt"_ "github.com/go-sql-driver/mysql""log""os"
)type PersonList struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`Sex int `json:"sex"`
}func main() {// 连接数据库db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test")if err != nil {log.Fatal("err1:", err)}defer db.Close()// 查询rows, err := db.Query("SELECT * FROM person")if err != nil {log.Fatal("err2:", err)}defer rows.Close()// 新建csvfile, err := os.Create("person.csv")if err != nil {log.Fatal("err3:", err)}defer file.Close()writer := csv.NewWriter(file)defer writer.Flush()// 写表头header := []string{"id","name","age","sex",}writer.Write(header)// 遍历,写入csvfor rows.Next() {var personlist = PersonList{}// 绑定err = rows.Scan(&personlist.Id,&personlist.Name,&personlist.Age,&personlist.Sex,)if err != nil {log.Fatal("err3:", err)}row := []string{fmt.Sprintf("%d", personlist.Id),personlist.Name,fmt.Sprintf("%d", personlist.Age),fmt.Sprintf("%d", personlist.Sex),}writer.Write(row)}err = rows.Err()if err != nil {log.Fatal("err4:", err)}
}
- 输出:
- 注意:
rows.Scan绑定字段,数据库中字段顺序应与绑定顺序相同
3 tip
python实现数据表转csv:https://blog.csdn.net/qq_45859826/article/details/131451336