postgresql - 如何一次性将多行插入 postgresQL

标签 postgresql go libpq pq

  1. 是否可以一次向 Postgres 数据库中插入多行?有人可以建议是否有办法将一片 slice 插入数据库。我为每一行创建了一个 slice ,并通过将所有行 slice 附加到它来创建另一个 slice (多行)。如何将 slice (多行)插入数据库?

  2. 当我创建行 slice 时,我使用的是 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 ($1, $2, $3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)`

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...)

https://play.golang.org/p/YqNJKybpwWB

关于postgresql - 如何一次性将多行插入 postgresQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130658/

相关文章:

sql - PostgreSQL 查询优化 - 我可以强制在查找表上使用索引吗?

Golang 数基转换

c++ - 从 C++ 程序执行时出现 psql\copy 命令错误

sql - 如何获取有关 PostgreSQL 中函数参数的定量和定性信息?

postgresql - 如何启用 pg_xlog 的自动清理

golang 模板 - 默认语义如何

qt - 链接到 libpq 失败,带有未解析的符号 _PQconnectdb

c - 如何从 PostgreSQL 的 libpq 中删除 PGPing 结果?

sql - PostgresQL 错误 : operator does not exist: integer = integer[]

go - 如何在 Golang 中转储结构的方法?