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

2023-12-05 0 642

前言

本文介绍两点:

  • 如何在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批量创建内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • Django如何批量创建Model

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Golang Golang使用CopyIn进行批量创建的示例代码 https://www.u-9.cn/jiaoben/golang/102161.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务