为了账号安全,请及时绑定邮箱和手机立即绑定

使用 pgx.CopyFrom 将 csv 数据批量插入到 postgres 数据库中

使用 pgx.CopyFrom 将 csv 数据批量插入到 postgres 数据库中

Go
温温酱 2022-12-19 19:55:14
我再次尝试将大量 csv 数据推送到 postgres 数据库中。过去,我创建了一个结构来保存数据,并在将数据放入数据库表之前将每一列解压缩到结构中,这工作正常,但是,我刚刚找到 pgx.CopyFrom* 并且看起来好像我应该能够让它更好地工作。到目前为止,我已经将表的列标题放入一段字符串中,将 csv 数据放入另一段字符串中,但我无法计算出将其推入数据库的语法。我发现这篇文章有点像我想要的,但使用 [][]interface{} 而不是 []strings。我到目前为止的代码是// loop over the lines and find the first one with a timestampfor {                        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。语法应该是什么?我是不是找错树了?
查看完整描述

1 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

我建议阅读您的 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 的[][]interface{}完整演示。


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


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 455 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号