Golang : GORM create record or insert new record into database example
Continuing from previous tutorial on how to read record from database with GORM. This time we learn how to create or insert new record into a database.
In this example, we will insert one record with GORM and also learn how to mitigate SQL table field name with underscore.
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)
// NOTE : In the struct, CreatedOn will be translated into created_on in sql level
type Activities struct {
Id int `sql:"AUTO_INCREMENT"`
Username string `sql:"varchar(50);unique"`
CreatedOn time.Time `sql:"timestamp"`
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(xxx.xxx.xxx.xxx:3306)/databasename?charset=utf8&parseTime=true")
if err != nil {
fmt.Println(err)
}
dbConn.DB()
dbConn.DB().Ping()
dbConn.DB().SetMaxIdleConns(10)
dbConn.DB().SetMaxOpenConns(100)
// omit/skip field with auto increment and those with blank/nil/empty data
activity := Activities{
Username: "testuser",
CreatedOn: time.Now().Local(),
Description: "Testing",
Visibility: "S",
}
dbConn.Create(&activity)
// Get the last record
dbConn.Last(&activity)
fmt.Println(activity)
}
NOTE : Without the &parseTime=true
parameter in the dbConn configuration. The GORM driver will have problem reading(scanning) and translating the SQL timestamp.
References :
See also : Golang : GORM read from database example
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
+31.7k Golang : Validate email address with regular expression
+6.3k Golang : Spell checking with ispell example
+23.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+21.1k Golang : How to read float value from standard input ?
+7.3k Gogland : Single File versus Go Application Run Configurations
+17.9k Golang : How to remove certain lines from a file
+32.8k Delete a directory in Go
+23.8k Golang : Find biggest/largest number in array
+21.4k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+9.1k Golang : How to protect your source code from client, hosting company or hacker?
+4.4k MariaDB/MySQL : How to get version information
+8.1k Golang : Count leading or ending zeros(any item of interest) example