LoginSignup
0
1

More than 3 years have passed since last update.

Goでデータベースの内容を取得する関数を作る

Last updated at Posted at 2020-10-14

データベースから目的の内容を全て取る関数について今から書きます。すでにデータベースには、なにか入っている状態でします

interface{} な変数を型が決まっている関数の引数にする
「Golang」 ×「Gorm」でシンプルに「Mysql」を操作する
【go + gin + gorm】webアプリにログイン機能を追加してみる
Goでの Mysql接続から構造体へのデータ割り当てまで
Gin と GORM で作るオレオレ構成 API


install
import (
    _ "github.com/go-sql-driver/mysql"// これは、自分で追加が必要
    "github.com/jinzhu/gorm"
)
// ないとき
//go get github.com/jinzhu/gorm
//go get github.com/go-sql-driver/mysql

まず、データベースと接続をします

main.go
func openGormDB() *gorm.DB { // localhost
    DBMS := "mysql"
    USER := "user"//mysqlのユーザー名
    PASS := "password"//パスワード
    PROTOCOL := "tcp(localhost:3306)"
    DBNAME := "sample"//データベース名

    CONNECT := USER + ":" + PASS + "@" + PROTOCOL + "/" + DBNAME + "?charset=utf8&parseTime=True&loc=Local"
    db, err := gorm.Open(DBMS, CONNECT)
    if err != nil {
        panic(err)
    }
    return db
}

これは、データベースの内容

main.go
type ShiromiyaChannelInfos struct {
    //ID              uint64
    ChannelID       string
    ChannelName     string
    ViewCount       uint `gorm:"type:int"`
    SubscriberCount uint `gorm:"type:int"`
    VideoCount      uint `gorm:"type:int"`
    CreatedAt       time.Time
}

データベースの内容を取る関数
テーブルごとに書かく

データベースの内容を取る関数
func GetDBShiro() []ShiromiyaChannelInfos/*<=①*/ {
    db := openGormDB()
    var shiroInfo []ShiromiyaChannelInfos/*<=①*/
    db.Find(&shiroInfo)/*<=①*/
    db.Close()
    return shiroInfo/*<=①*/

データベースに接続して目的のテーブルの内容を全て取得する関数

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