登录
首页 >  Golang >  Go问答

将CSV数据批量导入PostgreSQL数据库

来源:stackoverflow

时间:2024-02-18 14:24:22 250浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《将CSV数据批量导入PostgreSQL数据库》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我再次尝试将大量 csv 数据推送到 postgres 数据库中。

过去,我创建了一个结构来保存数据,并在将批次放入数据库表之前将每一列解压到结构中,并且工作正常,但是,我刚刚找到了 pgx.copyfrom* 和看来我应该能够让它工作得更好。

到目前为止,我已将表的列标题放入一片字符串中,并将 csv 数据放入另一片字符串中,但我无法计算出将其推入数据库的语法。

我发现这篇文章可以实现我想要的功能,但使用 [][]interface{} 而不是 []strings。

到目前为止我的代码是

// loop over the lines and find the first one with a timestamp
for {                
        line, err := csvReader.Read()                   
        if err == io.EOF { 
           break
        } else if err != nil {
           log.Error("Error reading csv data", "Loading Loop", err)
        }

       // see if we have a string starting with a timestamp
       _, err := time.Parse(timeFormat, line[0])
       if err == nil {
          // we have a data line
          _, err := db.CopyFrom(context.Background(), pgx.Identifier{"emms.scada_crwf.pwr_active"}, col_headings, pgx.CopyFromRows(line))    
      }
   }

}

但是 pgx.copyfromrows 需要 [][]interface{} 而不是 []string。

语法应该是什么?我是不是找错树了?


正确答案


我建议读取您的 csv 并为您读取的每条记录创建一个 []interface{},将 []interface{} 附加到行集合 ([][]interface{}),然后将行传递给 pgx。

var rows [][]interface{}

// read header outside of CSV "body" loop
header, _ := reader.Read()

// inside your CSV reader "body" loop...
    row := make([]interface{}, len(record))

    // use your logic/gate-keeping from here

    row[0] = record[0] // timestamp

    // convert the floats
    for i := 1; i < len(record); i++ {
        val, _ := strconv.ParseFloat(record[i], 10)
        row[i] = val
    }

    rows = append(rows, row)

...

copyCount, err := conn.CopyFrom(
    pgx.Identifier{"floaty-things"},
    header,
    pgx.CopyFromRows(rows),
)

我无法模拟整个程序,但这里有一个将 csv 转换为 [][]接口{}, https://go.dev/play/p/efbiFN2FJMi 的完整演示。

并检查文档,https://pkg.go.dev/github.com/jackc/pgx/v4

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>