如何一次性将多行插入 postgres SQL
How to insert multiple rows into postgres SQL in a go
是否可以一次将多行插入到 Postgres 数据库中?有人可以建议是否有办法将一片切片插入数据库。我为每一行创建了一个切片,并通过将所有行切片附加到它来创建另一个切片(多行)。如何将切片(多行)插入数据库?
创建行切片时,我使用的是 row := []interface{}{}
。因为我在每一行中都有字符串和 int 字段。看来我
插入数据时出错,错误是 unsupported type []interface {}, a slice of interface
实施:
rowdata := []interface{}{}
row := []interface{}{data.ScenarioUUID, data.Puid, data.Description, data.Status, data.CreatedBy, data.CreatedAt, data.UpdatedBy, data.UpdatedAt, data.ScopeStartsAt, data.ScopeEndsAt, Metric, MetricName, Channel, date, timeRangeValue}
rowdata = append(rowdata, row)
qry2 := `INSERT INTO sample (scenarioUuid,
puId,
description,
status,
createdBy,
createdAt,
updatedBy,
updatedAt,
scopeStartsAt,
scopeEndsAt,
metric,
metric_name,
channel,
time,
value) VALUES (, , ,,,,,,,,,,,,)`
if _, err := db.Exec(qry2, rowdata); err != nil {
panic(err)
你可以这样做:
samples := // the slice of samples you want to insert
query := `insert into samples (<the list of columns>) values `
values := []interface{}{}
for i, s := range samples {
values = append(values, s.<field1>, s.<field2>, < ... >)
numFields := 15 // the number of fields you are inserting
n := i * numFields
query += `(`
for j := 0; j < numFields; j++ {
query += `$`+strconv.Itoa(n+j+1) + `,`
}
query = query[:len(query)-1] + `),`
}
query = query[:len(query)-1] // remove the trailing comma
db.Exec(query, values...)
是否可以一次将多行插入到 Postgres 数据库中?有人可以建议是否有办法将一片切片插入数据库。我为每一行创建了一个切片,并通过将所有行切片附加到它来创建另一个切片(多行)。如何将切片(多行)插入数据库?
创建行切片时,我使用的是
row := []interface{}{}
。因为我在每一行中都有字符串和 int 字段。看来我 插入数据时出错,错误是unsupported type []interface {}, a slice of interface
实施:
rowdata := []interface{}{}
row := []interface{}{data.ScenarioUUID, data.Puid, data.Description, data.Status, data.CreatedBy, data.CreatedAt, data.UpdatedBy, data.UpdatedAt, data.ScopeStartsAt, data.ScopeEndsAt, Metric, MetricName, Channel, date, timeRangeValue}
rowdata = append(rowdata, row)
qry2 := `INSERT INTO sample (scenarioUuid,
puId,
description,
status,
createdBy,
createdAt,
updatedBy,
updatedAt,
scopeStartsAt,
scopeEndsAt,
metric,
metric_name,
channel,
time,
value) VALUES (, , ,,,,,,,,,,,,)`
if _, err := db.Exec(qry2, rowdata); err != nil {
panic(err)
你可以这样做:
samples := // the slice of samples you want to insert
query := `insert into samples (<the list of columns>) values `
values := []interface{}{}
for i, s := range samples {
values = append(values, s.<field1>, s.<field2>, < ... >)
numFields := 15 // the number of fields you are inserting
n := i * numFields
query += `(`
for j := 0; j < numFields; j++ {
query += `$`+strconv.Itoa(n+j+1) + `,`
}
query = query[:len(query)-1] + `),`
}
query = query[:len(query)-1] // remove the trailing comma
db.Exec(query, values...)