Golang使用CopyIn进行批量创建的示例代码

来自:网络
时间:2023-07-24
阅读:

前言

本文介绍两点:

  • 如何在golang中使用copyin
  • 如何对特殊字符jsonb进行插入(需要显式强制转化为string类型)
package main
import (
    "fmt"
    "github.com/jinzhu/gorm"
    "github.com/lib/pq"
)
func main() {
    fmt.Println(1)
    dbConfig := fmt.Sprintf("host=localhost user=postgres dbname=postgres sslmode=disable password=123456 application_name=xxx")
    fmt.Println("db:", dbConfig)
    engine, e := gorm.Open("postgres", dbConfig)
    if e != nil {
        panic(e)
    }
    driverdb := engine.DB()
    tx,e := driverdb.Begin()
    if e!=nil {
        panic(e)
    }
    // 表名为test
    // 字段为 age-integer, name-varchar, attach-jsonb
    stmt, e := tx.Prepare(pq.CopyIn("test", "age","name", "attach"))
    if e != nil {
        tx.Rollback()
        panic(e)
    }
    defer stmt.Close()
    for i := 0; i < 10000; i++ {
       var attach = map[string]interface{}{
            "money": 19,
            "mother": "芳芳",
        }
        buf, _ := json.Marshal(attach)
        _, e := stmt.Exec(i, "张三", string(buf))
        if e != nil {
            tx.Rollback()
            panic(e)
        }
    }
    // stmt.Exec 必须空执行一次表示结束。否则tx.Commit将阻塞
    stmt.Exec()
    tx.Commit()
}
返回顶部
顶部