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

我再次尝试将大量 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。


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


温温酱
浏览 456回答 1
1回答

翻过高山走不出你

我建议阅读您的 CSV 并为您阅读的每条记录创建一个[]interface{},将其附加[]interface{}到行集合 ( [][]interface{}),然后将行传递给 pgx。var rows [][]interface{}// read header outside of CSV "body" loopheader, _ := reader.Read()// inside your CSV reader "body" loop...&nbsp; &nbsp; row := make([]interface{}, len(record))&nbsp; &nbsp; // use your logic/gate-keeping from here&nbsp; &nbsp; row[0] = record[0] // timestamp&nbsp; &nbsp; // convert the floats&nbsp; &nbsp; for i := 1; i < len(record); i++ {&nbsp; &nbsp; &nbsp; &nbsp; val, _ := strconv.ParseFloat(record[i], 10)&nbsp; &nbsp; &nbsp; &nbsp; row[i] = val&nbsp; &nbsp; }&nbsp; &nbsp; rows = append(rows, row)...copyCount, err := conn.CopyFrom(&nbsp; &nbsp; pgx.Identifier{"floaty-things"},&nbsp; &nbsp; header,&nbsp; &nbsp; pgx.CopyFromRows(rows),)我无法模拟整个程序,但这里有一个将 CSV 转换为 https://go.dev/play/p/efbiFN2FJMi 的[][]interface{}完整演示。并查看文档https://pkg.go.dev/github.com/jackc/pgx/v4。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go