如何导入CSV并保存在数据库中

nyt*_*o04 8 go

这是我的代码第一部分的片段

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)中的代码。

der*_*unk 5

Go MySQL 驱动程序支持从文件加载:

请参阅https://github.com/go-sql-driver/mysql#load-data-local-infile-supporthttps://godoc.org/github.com/go-sql-driver/mysql#RegisterLocalFile

RegisterLocalFile 将给定的文件添加到文件白名单中,以便“LOAD DATA LOCAL INFILE”可以使用它。或者,您可以允许使用带有 DSN 参数“allowAllFiles=true”的所有本地文件

filePath := "/home/gopher/data.csv" mysql.RegisterLocalFile(filePath)
err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE
foo") if err != nil { ...
Run Code Online (Sandbox Code Playgroud)


Eze*_*eno 2

每个数据库引擎都有不同的方式来优化导入 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