2
2

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でcsvデータを読み取り、DBに保存

Posted at

はじめに

csvのデータをDBに保存しなけらばならなくなり
csvデータをDBに保存する 機能を作成しましたのでメモ程度に記載します。

環境は echo+gorm+docker です

##ディレクトリ

Project
├──docker
|    ├──go
|    |   └──Dockerfile
|    └──mysql
|     
├──docker-compose.yml
└── src | 
     └──go
        ├── controllers
        ├── database
        ├── csv
        |    └──schooldata.csv
        |
        ├── db (migationとかseedとか)
        ├── dbconfig.yml
        ├── go.mod
        ├── go.sum
        ├── main.go
        └── fresh.conf

##実行するgoファイル

今回は
schoolsというテーブルに
csvの学校データを大量に読み込むという想定で作成しました。

package main

import (
    "encoding/csv"
    "os"
    "fmt"
    "api/database"
    "github.com/jinzhu/gorm"
   _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Schools struct {
    Area   string    `gorm:"column:area"` //学校の所在地
    Name   string    `gorm:"column:name"` //学校名
}

func main() {

    db := dbconnect.Connect()
    defer db.Close()
    
    if err := readingcsv(db);err != nil {
        fmt.Println(err)
    }

}

func readingcsv(db *gorm.DB) error {

   
    //読み込むCSVファイルを記載
    csvFile, err := os.Open("csv/schooldata.csv") 
    fmt.Println("csvは読みこめませんでした")
    if err != nil {
        return err
    }
    defer csvFile.Close()

    reader := csv.NewReader(csvFile)
    reader.FieldsPerRecord = -1
    record, err := reader.ReadAll()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    for i := 0; i < len(record); i++ {
        fmt.Println(record[i][0])
        fmt.Println(record[i][1])

        schools := Schools{Area: (record[i][0]),Name:(record[i][1])}
    
        if err := db.Create(&schools).Error; err != nil {
            fmt.Printf("%+v", err)
        }
    }
    return nil
}

あとは実行するだけ

docker-compose exec go go run main.go
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?