How to use GORM packages in Golang

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

  • GORM
  • SQLITE drive

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)
  }

How to solve gcc error in Golang -Windows

How to solve gcc compiler error in Golang on windows machine


On windows you may got the gcc compiler error while trying to add packages like “gorm.io/driver/sqlite” in Golang. The cause for the error is that, underlying package require the gcc C compiler which is not installed on Windows PC by default.

How to solve

We need to install the C compiler on Windows machine and also need to add the path to environment variable.

The easiest way to install the mingw package from tmd-gcc repository.

Also add the path to the bin folder as follows in environment variables.

C:\TDM-GCC-64\bin