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

Jacinthe ·
更新时间:2024-09-20
· 341 次阅读

前言

本文介绍两点:

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



示例 golang

需要 登录 后方可回复, 如果你还没有账号请 注册新账号