Create a function to get the contents of the database in Go

I'm going to write about a function that takes all the desired content from the database. I already have something in the database

Make an interface {} variable an argument of a function with a fixed type Simple operation of "Mysql" with "Golang" x "Gorm" [Go + gin + gorm] Try adding a login function to the web application From Mysql connection in Go to data allocation to structure Oreore configuration API made with Gin and GORM


install


import (
    _ "github.com/go-sql-driver/mysql"//This needs to be added by myself
	"github.com/jinzhu/gorm"
)
//When not
//go get github.com/jinzhu/gorm
//go get github.com/go-sql-driver/mysql

First, connect to the database

main.go


func openGormDB() *gorm.DB { // localhost
	DBMS := "mysql"
	USER := "user"//mysql username
	PASS := "password"//password
	PROTOCOL := "tcp(localhost:3306)"
	DBNAME := "sample"//Database name

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

This is the contents of the database

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
}

Function that takes the contents of the database Write for each table

Function that takes the contents of the database


//I have to write a function like this one many times
func GetDBShiro() []ShiromiyaChannelInfos/*<=①*/ {
	db := openGormDB()
	var shiroInfo []ShiromiyaChannelInfos/*<=①*/
	db.Find(&shiroInfo)/*<=①*/
	db.Close()
	return shiroInfo/*<=①*/

func GetDBHashi() []HashibaChannelInfos/*<=①*/ {
	db := openGormDB()
	var hashiInfo []HashibaChannelInfos/*<=①*/
	db.Find(&hashiInfo)/*<=①*/
	defer db.Close()
	return hashiInfo/*<=①*/
}

A function that connects to a database and gets all the contents of the target table Only the place where it was different from ① above The rest is almost the same

I have to write something like the above (function that takes the contents of the database) many times, so I summarized it

main.go


//This is the finished product
func AllGetDBChannelInfo(chInfo string) (interface{}, error) {
	db := openGormDB()
	defer db.Close()

	switch chInfo {
	case "ShiromiyaChannelInfos":
		var channelInfo []entity.ShiromiyaChannelInfos
		db.Find(&channelInfo)
		return channelInfo, nil
	case "HashibaChannelInfos":
		var channelInfo []entity.HashibaChannelInfos
		db.Find(&channelInfo)
		return channelInfo, nil
	case "ChannelInfos":
		var videoInfo []entity.VideoInfos
		db.Find(&videoInfo)
		return videoInfo, nil
	default:
		return nil, errors.New("That db_no name")
	}
}

problem: AllGetDB must overwrite AllGetDB later when adding a function

GetDB has many functions with many duplicates. But you don't have to overwrite the function, just add it

Recommended Posts

Create a function to get the contents of the database in Go
[Go] Create a CLI command to change the extension of the image
How to get the vertex coordinates of a feature in ArcPy
I tried to create a Python script to get the value of a cell in Microsoft Excel
Create a command to get the work log
[Linux] Command to get a list of commands executed in the past
How to create a wrapper that preserves the signature of the function to wrap
Function to extract the maximum and minimum values ​​in a slice with Go
Create a function to visualize / evaluate the clustering result
Create a function in Python
How to get the number of digits in Python
Try to get the contents of Word with Golang
Create a filter to get an Access Token in the Graph API (Flask)
How to get a list of files in the same directory with python
Various methods to numerically create the inverse function of a certain function Part 1 Polynomial regression
Try to get the function list of Python> os package
Get the number of specific elements in a python list
I made a function to check the model of DCGAN
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
Let's create a function to hold down Button in Tkinter
How to get a quadratic array of squares in a spiral!
How to connect the contents of a list into a string
Get the value of a specific key up to the specified index in the dictionary list in Python
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
The story I was addicted to when I specified nil as a function argument in Go
I want to get the name of the function / method being executed
I tried to get a database of horse racing using Pandas
How to determine the existence of a selenium element in Python
I tried to get the index of the list using the enumerate function
How to get all the possible values in a regular expression
How to check the memory size of a variable in Python
Output the contents of ~ .xlsx in the folder to HTML with Python
How to check the memory size of a dictionary in Python
[TensorFlow 2] How to check the contents of Tensor in graph mode
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
How to create a large amount of test data in MySQL? ??
The easiest way to get started in Slack socket mode (Go)
Attempt to extend a function in the library (add copy function to pathlib)
[Python] A simple function to find the center coordinates of a circle
[Python] A program that rotates the contents of the list to the left
Get the number of readers of a treatise on Mendeley in Python
How to get a stacktrace in python
Get the filename of a directory (glob)
Get a capture of the entire web page in Selenium Python VBA
Click the Selenium links in order to get the elements of individual pages
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to compare if the contents of the objects in scipy.sparse.csr_matrix are the same
Test & Debug Tips: Create a file of the specified size in Python
I want to sort a list in the order of other lists
Added a function to register desired shifts in the Django shift table
Get a datetime instance at any time of the day in Python
I made a program to check the size of a file in Python
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
I tried to display the altitude value of DTM in a graph
Python: I want to measure the processing time of a function neatly
What is the fastest way to create a reverse dictionary in python?
I made a function to see the movement of a two-dimensional array (Python)
The story of creating a store search BOT (AI LINE BOT) for Go To EAT in Chiba Prefecture (1)
How to copy and paste the contents of a sheet in Google Spreadsheet in JSON format (using Google Colab)