0
1

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.

gormでcsvをdatabaseに入れる

Last updated at Posted at 2020-05-22

仕事で今だにexcelファイルを何枚も用意して管理をしているデータがあったので
管理システム作ることにしました。
その際に現状のデータをcsvに変えてgoでデータベースへぶち込んだ際の備忘録兼個人メモです。
至らぬところばかりですが、ご了承ください。

gormを用いてmysqlに入れてます

go get -u github.com/jinzhu/gorm
sample.csv
佐藤,24,神奈川
向井,19,香川
田中,44,長野

tree

csv_to_db
├── db_connect
│   └── db_connect.go
├── sample.csv
└── main.go
db_connect.go
package database_connect

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

func GormConnect() *gorm.DB {
	DBMS := "mysql"
	USER := "root"
	PASS := "You Pass"
	PROTOCOL := "tcp(0.0.0.0:3306)"
	DBNAME := "DB name"

	CONNECT := USER + ":" + PASS + "@" + PROTOCOL + "/" + DBNAME
	db, err := gorm.Open(DBMS, CONNECT)

	if err != nil {
		panic(err.Error())
	}
	return db
}
main.go
package main

import (
	"encoding/csv"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/sudyusuk/csv_to_db/db_connect"
	"os"
	"strconv"
)

type Databases struct {
	UserDatabase *gorm.DB
}

//データベース側は複数系じゃないといけない e.g.:table_names
type TableName struct {
	Name      string    `gorm:"column:name"`
	Age       int       `gorm:"column:age"`
	Address   string    `gorm:"column:address"`
}

func main() {

	user_db := database_connect.GormConnect
	databases := Databases{user_db()}

	if err := databases.readJson("./sample.csv");err != nil {
		fmt.Println(err)
	}

}

func (d *Databases) readJson(path string) error {

	csvFile, err := os.Open(path)
	if err != nil {
		return err
	}
	defer csvFile.Close()

	reader := csv.NewReader(csvFile)
	reader.FieldsPerRecord = -1

	csvData, err := reader.ReadAll()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for _, data := range csvData {
		age ,_ := strconv.Atoi(data[1])
       //intに変換

		oneLine := CreateOneLine(data[0],age,data[2])
		d.CreateDatabase(*oneLine)
	}
	return nil
}

//ここ作らなくてもいいけど、分かりやすく見やすいから。
//レコードを作る
func CreateOneLine(name string,age int ,address string) *TableName {
	return &TableName{name,age,address}
}

//保存
func (d *Databases) CreateDatabase(oneLine TableName) {
	d.UserDatabase.Create(&oneLine)
}

以上です。。
陳腐なコードですので気になるところばかりだと思いますが、その際はご教授いただけると嬉しいです。
goは楽しい

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?