我再次尝试将大量csv数据放入postgres数据库。
在过去,我创建了一个结构来保存数据,并将每一列都解压到结构中,然后再将其插入数据库表中,这是很好的,但是,我刚刚找到了pgx.CopyFrom*,看起来我应该能够使它更好地工作。
到目前为止,我已经将表的列标题转换为字符串片段,将csv数据放到另一段字符串中,但我无法确定将其放入数据库的语法。
我已经找到了this post,它可以做我想做的事情,但是使用接口{}而不是[]字符串。
到目前为止,我掌握的代码是
// 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需要接口{} not []字符串。
语法应该是什么?我撞错树了吗?
发布于 2022-06-06 07:51:09
我建议读取您的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转换为[][]interface{},https://go.dev/play/p/efbiFN2FJMi的完整演示。
https://stackoverflow.com/questions/72513782
复制相似问题