文章目录
- 1 基本结构
- 1.1 数据
- 1.2 数据结构
- 2 代码
- 3 tip
1 基本结构
1.1 数据
1.2 数据结构
2 代码
- 代码:
package main
import (
"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()
// 新建csv
file, 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)
// 遍历,写入csv
for 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