2 回答
TA贡献1712条经验 获得超3个赞
rows, _ := db.Query("SELECT * FROM orderTest limit 100;")
err := sqltocsv.WriteFile("orderTest.csv", rows)
if err != nil {
panic(err)
}
columns, _ := rows.Columns()
count := len(columns)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for rows.Next() {
for i := range columns {
valuePtrs[i] = &values[i]
}
rows.Scan(valuePtrs...)
for i, col := range columns {
val := values[i]
b, ok := val.([]byte)
var v interface{}
if ok {
v = string(b)
} else {
v = val
}
fmt.Println(col, v)
}
}
}
我的目标是让 OrdeTest.csv 文件在运行 main.go 时自动创建
TA贡献1852条经验 获得超1个赞
sqltocsv.WriteFile(...)如果文件不存在,应该为您创建该文件。
在底层,它只使用os.Create(...)标准库中的内容。
github.com/joho/sqltocsv/sqltocsv.go:
// WriteFile writes the CSV to the filename specified, return an error if problem
func (c Converter) WriteFile(csvFileName string) error {
f, err := os.Create(csvFileName)
if err != nil {
return err
}
err = c.Write(f)
if err != nil {
f.Close() // close, but only return/handle the write error
return err
}
return f.Close()
}
文档os.Create(...):
// Create creates the named file with mode 0666 (before umask), truncating
// it if it already exists. If successful, methods on the returned
// File can be used for I/O; the associated file descriptor has mode
// O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
- 2 回答
- 0 关注
- 118 浏览
添加回答
举报