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

前言

本文介绍两点:

  • 如何在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()
}

到此这篇关于Golang使用CopyIn进行批量创建的示例代码的文章就介绍到这了,更多相关Golang CopyIn批量创建内容请搜索aitechtogether.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持aitechtogether.com!

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年12月27日
下一篇 2023年12月27日

相关推荐