Setting up GORM
The first thing we need to do with GORM is to instantiate it and open the database connection. GORM uses the standard Go SQL package under the hood to open the connection, so let’s see how we connect to a database using GORM:
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
)
func main() {
db, err := gorm.Open(sqlite.Open("my-project.db"), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
}
In the example, we open the database connection using the sqlite package and pass that connection to GORM’s Open function. It gets us to our GORM db instance, where we can use it. But before we start, we need to define and register our models. Let’s see how to do that.