Golang : GORM read from database example
Just a simple tutorial on how to use GORM(Golang Object Relational Map) to connect to a MySQL/MariaDB database and read data from it.
Here you go!
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"time"
)
// Activities table SQL :
// id bigint(20) AUTO_INCREMENT
// username varchar(50)
// created_on timestamp
// action char(1)
// description varchar(300)
// visibility char(1)
type Activities struct {
Id int `sql:"AUTO_INCREMENT"`
Username string `sql:"varchar(50);unique"`
Created_On time.Time
Action string `sql:"type:char(1)"`
Description string `sql:"type:varchar(300)"`
Visibility string `sql:"type:char(1)"`
}
func main() {
dbConn, err := gorm.Open("mysql", "username:password@tcp(xx.xxx.xxx.xxx:3306)/database_name?charset=utf8&parseTime=true")
if err != nil {
fmt.Println(err)
}
// init
dbConn.DB()
dbConn.DB().Ping()
dbConn.DB().SetMaxIdleConns(10)
dbConn.DB().SetMaxOpenConns(100)
activity := Activities{} // a record
// get first record
dbConn.First(&activity)
fmt.Println(activity)
fmt.Println("------------------------------")
// get all records
activities := []Activities{} // a slice
//dbConn.Find(&activities)
//fmt.Println(activities)
// get records from record offset 1 to 10
// useful for pagination purpose! - just need to calculate the offset and limit dynamically
dbConn.Limit(10).Order("id asc").Find(&activities).Offset(1).Order("id asc").Find(&activities)
for _, v := range activities {
fmt.Println("Id : ", v.Id)
fmt.Println("Username : ", v.Username)
fmt.Println("Created On : ", v.Created_On)
fmt.Println("Action : ", v.Action)
fmt.Println("Desription : ", v.Description)
fmt.Println("Visibility : ", v.Visibility)
}
}
NOTE : Without the &parseTime=true
parameter in the dbConn configuration. Your driver will have problem reading(scanning) and translating the SQL timestamp.
References :
https://en.wikipedia.org/wiki/Object-relational_mapping
https://www.socketloop.com/tutorials/golang-connect-to-database-mysql-mariadb-server
See also : Golang : Connect to database (MySQL/MariaDB) server
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.8k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+7.7k Swift : Convert (cast) String to Double
+9.2k Golang : Find the length of big.Int variable example
+36k Golang : How to split or chunking a file to smaller pieces?
+3.5k Golang : Switch Redis database redis.NewClient
+17.9k Golang : Check if a directory exist or not
+6.6k Golang : Get expvar(export variables) to work with multiplexer
+8.8k Golang : Go as a script or running go with shebang/hashbang style
+4.2k Golang : Valued expressions and functions example
+12.1k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+4.7k Javascript : How to get width and height of a div?
+6.7k Golang : Normalize email to prevent multiple signups example