How to use GORM package with SQLite database in Golang
Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.
GORM
GORM is a ORM in Golang which help to generate and manipulate databases such as MySql, SQL server, SQLite etc. It will automatically create table for storing data based on ORM models.
In this example we are going to setup a SQLite database.
To make use of GORM first we need to add two packages
While using SQLite driver in Window there can be an gcc compiler error, please refer post link down below this post.
Let’s add the packages
go get gorm.io/driver/sqlite
gorm.io/driver/sqlite
Initialize and Migrate database with the ORM
First up all we need to generate a Model/Schema for our table and then initialize the database.
type Product struct {
gorm.Model
Code string
Price uint
}
With Automigrate GORM will make necessary changes in the database structure, only if there is a change occurs in the Schema.
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(&Product{})
The complete code for setup GORM is following.
Complete code
//main.go
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "D42", Price: 100})
// Read
var product Product
db.First(&product, 1) // find product with integer primary key
fmt.Println(product.Price)
db.First(&product, "code = ?", "D42") // find product with code D42
Update - update product's price to 200
db.Model(&product).Update("Price", 200)
db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
Delete - delete product
db.Delete(&product, 1)
}