Mastering MySQL Connections in Go: From Raw SQL to GORM ORM

Learn how to connect Go applications to MySQL using the native driver and the GORM ORM, covering driver installation, basic connection code, database configuration, query execution, and best practices for model definition and handling common pitfalls.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering MySQL Connections in Go: From Raw SQL to GORM ORM

Go Connect MySQL

First we show how to use Golang to connect to MySQL.

Install the required driver go get github.com/go-sql-driver/mysql Import the necessary packages

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

Basic connection code

func main() {
    // "username:password@tcp(host:port)/dbname"
    db, _ := sql.Open("mysql", "root:pwd@(localhost)/database")
    defer db.Close()
    err := db.Ping()
    if err != nil {
        fmt.Println("Open database fail !")
        return
    }
    fmt.Println("Connection success !")
}

Example: Table creation

Create a test database with a user table containing fields id, name, age, sex, phone.

Database connection helper

Define constants for configuration and implement InitDB and Query functions.

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/pkg/errors"
    "strings"
)

const (
    userName = "root"
    password = "******"
    ip       = "127.0.0.1"
    port     = "3306"
    dbName   = "test"
)

var DB *sql.DB

type User struct {
    id    int64
    name  string
    age   int8
    sex   int8
    phone string
}

func InitDB() {
    path := strings.Join([]string{userName, ":", password, "@tcp(", ip, ":", port, ")/", dbName, "?charset=utf8"}, "")
    DB, _ = sql.Open("mysql", path)
    DB.SetConnMaxLifetime(100)
    DB.SetMaxIdleConns(10)
    if err := DB.Ping(); err != nil {
        fmt.Println("open database fail !")
        return
    }
    fmt.Println("connection success !")
}

func Query() {
    var user User
    rows, e := DB.Query("select * from user where id in (1,2,3)")
    if e == nil {
        errors.New("query incur error")
    }
    for rows.Next() {
        e := rows.Scan(&user.sex, &user.phone, &user.name, &user.id, &user.age)
        if e != nil {
            fmt.Println(user.sex, user.phone, user.name, user.id, user.age)
        }
    }
    rows.Close()
}

func main() {
    InitDB()
    Query()
    defer DB.Close()
}

The above demonstrates the basic method of connecting Go to MySQL. Next we look at using GORM.

GORM

What is ORM

Object-Relational Mapping (ORM) bridges relational databases and object‑oriented programming languages, allowing developers to work with database records as native objects.

Advantages

Improves development efficiency and reduces cost.

Enables object‑oriented programming.

Provides portability.

Allows easy addition of features such as caching.

Eliminates repetitive SQL code.

Reduces development time and cost.

Handles vendor‑specific SQL differences.

Disadvantages

Learning curve can reduce short‑term productivity.

Less visibility into actual SQL executed.

Potential performance overhead.

Complex queries may be slower than raw SQL.

GORM Introduction

GORM is a powerful, developer‑friendly ORM library for Go that supports major databases such as MySQL, PostgreSQL, SQLite, SQL Server, and TiDB.

Installation

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

Connecting MySQL with GORM

The connection code is similar to the basic method.

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func main() {
    dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}
Note: To handle time.Time correctly, include the parseTime parameter and use charset=utf8mb4 for full UTF‑8 support.

GORM Model Definition

Models are Go structs that map to database tables. GORM follows “convention over configuration”: the field ID is the primary key, struct names become snake_case plural table names, and fields become snake_case columns. Timestamp fields CreatedAt and UpdatedAt are tracked automatically.

gorm.Model

GORM provides a built‑in gorm.Model struct with common fields.

type Model struct {
    ID        uint           `gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt gorm.DeletedAt `gorm:"index"`
}

You can embed it in your own structs:

type User struct {
    gorm.Model
    Name string
}

Or define a custom struct without embedding gorm.Model.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentmysqlORMGORMDatabase Connection
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.