3
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.

GormからRDSのmysqlデータベースにアクセスするとき

Posted at

当たり前かもしれませんが、意外と情報がなくててこずったのでここにメモっておきます。

user: dbのユーザーネーム
password: dbのパスワード
port: 3306とかのポート
dbName: データベースの名前
dbURL: xxxx.xxxx.us-east-2.rds.amazonaws.com のようなrdsのURL

sql_handler.go
import (
	"os"
	"time"

	"gorm.io/gorm"

	"gorm.io/driver/mysql"
)


// NewSQLHandler ...
func NewSQLHandler() *SQLHandler {
	user := os.Getenv("DB_USERNAME")
	password := os.Getenv("DB_PASSWORD")
	host := os.Getenv("DB_HOST")
	port := os.Getenv("DB_PORT")
	dbName := os.Getenv("DB_DATABASE")
	dbURL := os.Getenv("DATABASE_URL")

	var db *gorm.DB
	var err error
	dsn := user + ":" + password + "@tcp(" + dbURL + ":" + port + ")/" + dbName + "?charset=utf8&parseTime=True&loc=Local"
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
}

参考

こちらのレポジトリが参考になりました、ありがとうございました。

3
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
3
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?