17
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】sqlxでBulk Insert

Posted at

概要

以下のようなテーブルがあるとします。

user
 - id
 - name

userテーブルに対して、以下のように複数のValueを一度にinsertをしたい。

INSERT INTO user (name)
VALUES ('tom'),('james'),('piyo'),('alex'),('josh');

上記をsqlxで実現する方法

実装

NamedExecを使って、以下のように実装する


import (
  "database/sql"
  "fmt"

  _ "github.com/lib/pq"
  "github.com/jmoiron/sqlx"
)

type User struct {
  ID int32 `db:"id"`
  Name string `db:"name"`
}

func main() {
  db, _ := sql.Open("postgres","user=postgres password=pw dbname=postgres sslmode=disable")
  
  userNames []string{"tom", "james", "piyo", "alex", "josh"}
  users := make([]User, len(userNames))
  for i, v := range users {
    users[i] = User{
      Name: v,
    }
  }

  query := `INSERT INTO user (name) VALUES (:name)`
  _, err := db.NamedExec(query, users)
  if err != nil {
    fmt.Println("エラーだよ")
  }
}


17
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?