Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Golang CopyIn批量创建

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

作者:fwhezfwhez

本文主要介绍了Golang使用CopyIn进行批量创建的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

本文介绍两点:

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批量创建内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文