package main
import (
"database/sql"
"encoding/csv"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"os"
"strconv"
)
var db *sql.DB
type User struct {
Uid int
Name string
Phone string
Email string
Password string
}
var u User
func init() {
db, _ = sql.Open("mysql",
"root:a123456@tcp(127.0.0.1:3306)/xxx")
}
func main() {
filename := "./exportUsers.csv"
users := queryMultiRow()
column := [][]string{{"手機號碼", "用戶UID", "Email", "用戶名"}}
for _, u := range users {
str := []string{}
str = append(str, u.Phone)
str = append(str, strconv.Itoa(u.Uid))
str = append(str, u.Email)
str = append(str, u.Name)
column = append(column, str)
}
ExportCsv(filename, column)
}
func ExportCsv(filePath string, data [][]string) {
fp, err := os.Create(filePath)
if err != nil {
log.Fatalf("建立檔案["+filePath+"]失敗,%v", err)
return
}
defer fp.Close()
fp.WriteString("\xEF\xBB\xBF")
w := csv.NewWriter(fp)
w.WriteAll(data)
w.Flush()
}
func queryMultiRow() ([]User) {
rows, err := db.Query("select uid,name,phone,email from `user` where uid > ?", 0)
if err != nil {
fmt.Printf("query failed, err:%v\n", err)
return nil
}
defer rows.Close()
users := []User{}
for rows.Next() {
err := rows.Scan(&u.Uid, &u.Name, &u.Phone, &u.Email)
users = append(users, u)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
return nil
}
}
return users
}