这是我的代码第一部分的片段
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
file, err := os.Open("Account_balances.csv")
if err != nil {
fmt.Println("Error", err)
return
}
defer file.Close()
reader := csv.NewReader(file)
record, err := reader.ReadAll()
if err != nil {
fmt.Println("Error", err)
}
for value:= range record{ // for i:=0; i<len(record)
fmt.Println("", record[value])
}
}
Run Code Online (Sandbox Code Playgroud)
我想编写将 CSV 文件保存在任何数据库(即 SQL、SQLite 或 PostgreSQL)中的代码。
Go MySQL 驱动程序支持从文件加载:
请参阅https://github.com/go-sql-driver/mysql#load-data-local-infile-support和https://godoc.org/github.com/go-sql-driver/mysql#RegisterLocalFile。
RegisterLocalFile 将给定的文件添加到文件白名单中,以便“LOAD DATA LOCAL INFILE”可以使用它。或者,您可以允许使用带有 DSN 参数“allowAllFiles=true”的所有本地文件
Run Code Online (Sandbox Code Playgroud)filePath := "/home/gopher/data.csv" mysql.RegisterLocalFile(filePath) err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") if err != nil { ...
每个数据库引擎都有不同的方式来优化导入 CSV。您应该使用它们,而不是编写自己的方法来读取 CSV 和批量插入记录。
参考文献:
MySQL:https://dev.mysql.com/doc/refman/5.7/en/load-data.html
PgSQL:https://www.postgresql.org/docs/current/static/sql-copy.html