我再次嘗試將大量 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。
語法應該是什么?我在吠叫錯誤的樹嗎?
uj5u.com熱心網友回復:
我建議閱讀您的 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://pkg.go.dev/github.com/jackc/pgx/v4。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486675.html
標籤:PostgreSQL CSV 去 pgx
上一篇:在python中從資料框中自動命名csv檔案而不從資料框中獲取索引和標題的方法
下一篇:將資料從第1行移到第0行
